[英]jQuery: Move a DIV to left when its child element comes close to right edge of its parent element (type of auto-scrolling)
[英]Selecting parent element with plain JavaScript and auto-scrolling to the last element
我做了刪除圖片刪除括號,但由於某種原因,它沒有刪除整個職位,只是跨度。 第二個問題是,我希望瀏覽器自動滾動到發布的最新評論,以便用戶無需使用我的溢出實現即可手動滾動查看最新評論。 下面是代碼。 主圖片和刪除按鈕是我計算機中的圖片。 請幫忙
function postcomment() { var time = new Date(); var h = time.getHours(); var m = time.getMinutes(); var s = time.getSeconds(); if (h > 12){ h = h - 12; } else if (m < 10){ m = "0" + m; } else if (s<10){ s = "0" + s; } var comment = document.getElementById('comment').value var comments = document.getElementById('wherecommentgoes'); comments.innerHTML += "Post: " + comment + "<span>"+"at "+ h+" : "+m+" : "+s+" " +"<span id ='pic' onclick='delte(this)'><img src='http://www.freeiconspng.com/uploads/remove-icon-png-23.png' width='50' height='50'></span>"+"</span>" + "<br>"; document.getElementById('comment').value=""; } function delte(x){ x.parentElement.remove(x); }
<div id="wherecommentgoes"></div> <textarea rows="4" cols="50" id="comment" placeholder="Enter Your Comment Here"></textarea <span id=""></span>> <button id="submitbutton" onclick="postcomment()">Post</button> </body> </html>
它不會刪除整個帖子,而只是刪除范圍。
那講得通。
您應該添加一個容器元素,並在每個注釋周圍添加一個類(而不是ID):
comments.innerHTML += "<div class='comment-container'> Post: " + comment + "<span>"+"at "+
h+" : "+m+" : "+s+" " +"<img id ='pic' onclick='delte(this)' src='./images/delete.jpg'>"+"</span>" + "</div>";
為了刪除注釋的wrapper元素(即圖像的父級的父級),即.comment-container
,您需要以下函數:
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
如果您願意使用jQuery,則將.comment-container作為目標將更加容易。
首先,將一個類添加到您的img元素中:
然后附加事件處理程序(首選非嵌入式JavaScript)
$('body').on('click', '.js-delete', function() {
$(this).closest('.comment-container').remove();
)};
為了滾動到最后一條注釋,請修改您的delte函數,如下所示:
function delte(x){
var parentContainer = $(this).closest('.comment-container');
var targetToScroll = parentContainer.last(); // we're caching the last comment
x.parentElement.remove(x);
if( targetToScroll.length ) { // if the element exists...
event.preventDefault();
realoffSet = targetToScroll.offset().top; // calculate the distance from the top
$("html, body").animate({scrollTop: realoffSet}, 500); // scroll to that point
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.