Как перейти к последнему div, который динамически добавляется? - PullRequest
1 голос
/ 18 марта 2020

Я добавил тег div в файл (chat. html (скажем)), и когда мы нажимаем на кнопку, я динамически добавляю строки в div в скрипте. Я добавил тег iframe в другой файл say (list. html) и назначил атрибут sr c для чата. html. Когда страница чата. html загружается, она не заканчивается до конца div, если мне не нужно прокручивать вручную до конца div. Вместо этого он должен автоматически прокрутить до конца div, а также всякий раз, когда div добавляется, он должен получить прокрутку до div.

//list.html page code
<body>
 <div class="row">
    <div class="col-lg-6 mx-auto mt-5">
        <iframe width="1000px" height="650px" src="EarlyChat.html" ></iframe>
    </div>
  </div>
</body>

//chat.html page code
<section style="padding: 50px 0 0 0">
 <div id="questions" style="margin-bottom: 85px !important;"></div>
   <div class="msg-box">
     <div class="form-group">
       <input type="text" class="input-box sty-one" id="message" placeholder="Enter message"> <button type="submit" class="btn btn-primary btn-lg mb-2" style="margin-top: 5px" onclick="sendmessage()">send</button> 
     </div>
    </div>
  </section>

function sendmessage(){

     db.collection("ChatRoom").doc(userid).collection("Cities").orderBy("Time")
     .onSnapshot(function(querySnapshot) {
        var store_row = document.createElement("questions");
        var store;
        $('#questions').empty();
        querySnapshot.forEach(function(doc) {
          typeofmessage = doc.data().SenderId;
                    time = doc.data().Time.toDate();
                    console.log("typeofmessage value is",typeofmessage,time);
                    message = doc.data().message;
                    console.log("messages")
                    store = document.createElement("div");
                    if(typeofmessage == "Df"){
                        // console.log("left")
                        leftids.push(message)
                        console.log("store.getAttributes",store.getAttribute.id)
                        store.setAttribute("class", "card no-border");
                        store.setAttribute("id", doc.id);
                        store.innerHTML = `<div class="container1 darker">
                                        <img src="assets/images/user1.png" alt="Avatar" style="width:100%;">
                                        <p class="text-left">` + message + `</p>
                                        <span class="time-left">` + time.getHours() + ":" + time.getMinutes()  + `</span>
                                        </div>`;

                    }
                    else if(typeofmessage == userid){
                        console.log("right")
                        rightids.push(message)
                        // store = document.createElement("div");
                        store.setAttribute("class", "card no-border");
                        store.setAttribute("id", doc.id);
                        store.innerHTML = `<div class="container1">
                                        <img src="assets/images/image 209.png" alt="Avatar" class="right" style="width:100%;">
                                        <p class="text-right">` + message + `</p>
                                        <span class="time-right">` + time.getHours() + ":" + time.getMinutes() + `</span>
                                        </div>`;
                    }
                    store_row.append(store);
                    console.log("storerow.count is",store_row)
                    document.getElementById("questions").innerHTML = store_row.innerHTML;

                });
            });
}

Ответы [ 2 ]

0 голосов
/ 18 марта 2020

Вы можете использовать метод window scrollTo и свойство offsetTop последнего элемента div для выполнения sh this.

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

Я упростил ваш пример, чтобы показать его в действии. Ниже я динамически добавляю элементы, сохраняя ссылку на последний элемент offsetTop, затем прокручивая до элементов offsetTop

Единственное предостережение - мне пришлось использовать setTimeout, чтобы убедиться, что новые элементы сделали это на DOM.

<!DOCTYPE html>
<html>
    <body>
        <h1>Hello World</h1>
    </body>
    <script>
        // Simulate an array of data to render new content
        const paragraphs = []
        let lastParagraphY = 0

        for (let i = 0; i < 20; i++) {
            paragraphs.push(`This is paragraph ${i}. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.`)
        }

        // Dynamically create new html nodes
        paragraphs.forEach((paragraph, index) => {
            const body = document.querySelector('body')
            const newParagraph = document.createElement('p')
            newParagraph.innerHTML = paragraph
            newParagraph.id = index
            body.appendChild(newParagraph)
            lastParagraphY = newParagraph.offsetTop
        })

        // Ensure the dynamic elements have rendered
        setTimeout(() => {
            window.scrollTo(0, lastParagraphY)
        })
    </script>
</html>
0 голосов
/ 18 марта 2020

Вы можете указать id или имя в атрибуте sr c, чтобы автоматически перейти к определенному тегу div. Сначала вы должны назначить разные идентификаторы для каждого тега div, а затем при нажатии кнопки добавить идентификатор последнего тега div в атрибут sr c iframe в списке. html, как показано ниже.

<iframe width="1000px" height="650px" src="EarlyChat.html#message1" ></iframe> // assuming message1 is id of last div tag.

Для получения дополнительной информации посетите эту ссылку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...