我試圖創建一個div,它有一個按鈕,點擊它會平滑滾動(僅用於審美目的)插入目標。代碼:平滑滾動到ID
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Smooth Scrolling DIV</title>
<style>
div {
height: 250px;
width: 500px;
overflow: auto;
border: 2px solid black;
position: relative;
top: calc(50vh - 125px);
left: calc(50vw - 250px);
margin: 0;
padding: 0;
}
p {
text-align: center;
font-family: arial;
font-size: xx-large;
margin: 0;
padding: 0;
}
span {
color: red;
}
</style>
</head>
<body>
<div>
<p>some text<br>
some text<br>
some text<br>
some text<br>
some text<br>
some text<br>
some text<br>
some text<br>
some text<br>
some text <button id="myButton" onclick="myFunction()">Click</button> <span id="insert2"></span>
</p>
</div>
<script>
var getInsert2 = document.getElementById("insert2");
function myFunction() {
getInsert2.innerHTML = "<br> some more text";
getInsert2.scrollIntoView({block: "end", behavior: "smooth"});
}
</script>
</body>
</html>
我試着用scrollIntoView選項,但支持的唯一瀏覽器是火狐。這還不夠好。所以我一直試圖實現jQuery來完成這一部分。我發現一段簡單的,每個人都好像是用但一直未能代碼搞清楚如何實現:
var $root = $("html, body");
$root.animate({
scrollTop: $($.attr(this, "insert2")).offset().top
}, 1000);
return false;
});
也許這是邏輯或語法,或兩者是怎麼回事錯了,因爲我嘗試插入它進入我的代碼。
'$($ .attr(this,「insert2」))'根本看不正確。你想要選擇什麼? –