当用户单击按钮时,我正在运行以下脚本,以滚动到页面上的特定div,以及其他一些无关的函数。
问题是,按钮本身应该始终在视图中,因此可以被垃圾邮件单击,导致页面在忙着来回移动到同一个位置时出现“滞后”。我想通过只在页面尚未位于特定位置时执行滚动来对抗这种行为。
不幸的是,我没有使用JavaScript/jQuery的实际经验,也没有找到这样的例子。
下面是我的示例代码:
<div id="navButton">Button</div>
<div id="listContent">Content that must be visible after button click goes here</div>脚本
window.onload=function(){
document.getElementById("navButton").onclick = function(){
$("html, body").animate({scrollTop: $("#listContent").offset().top -165}, 400);
}
}发布于 2016-02-11 12:19:27
也许这个例子能帮你..。首先更改散列,然后侦听hashchange事件。当您重新加载页面时,它将向下滚动到您的锚上。
$(document).ready(function() {
// check for hash when page has loaded
if (getHash() != null) {
checkForScrolling();
}
});
// check for hash when hash has changed
window.onhashchange = function() {
checkForScrolling();
};
// return hash if so or null if hash is empty
function getHash() {
var hash = window.location.hash.replace('#', '');
if (hash != '') {
return hash;
} else {
return null;
}
}
// this function handles your scrolling
function checkForScrolling() {
// first get your element by attribute selector
var elem = $('[data-anchor="' + getHash() + '"]');
// cheeck if element exists
if (elem.length > 0) {
$('html, body').stop().animate({
scrollTop: elem.offset().top
}, 300);
}
} body {
font-family: Helvetica
}
section {
position: relative;
margin-bottom: 10px;
padding: 20px;
height: 300px;
background-color: #eee;
}
section a {
display: block;
position: absolute;
bottom: 10px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1 data-anchor="start">Smooth Scrolling</h1>
<ul>
<li><a href="#1">Scroll to Anchor 1</a>
</li>
<li><a href="#2">Scroll to Anchor 2</a>
</li>
<li><a href="#3">Scroll to Anchor 3</a>
</li>
</ul>
<section>
<h2 data-anchor="1">First Anchor</h2>
<a href="#start">Back to top</a>
</section>
<section>
<h2 data-anchor="2">Second Anchor</h2>
<a href="#start">Back to top</a>
</section>
<section>
<h2 data-anchor="3">Third Anchor</h2>
<a href="#start">Back to top</a>
</section>
</div>
发布于 2016-02-11 12:07:27
如果成功的话,试试这个
<div id="navButton" onclick="moveElement('listContent');">Button</div>
<div id="listContent">Content that must be visible after button click goes here</div>您需要包含在这个脚本代码中的jquery。
function moveElement(divId) {
$('html, body').animate({
scrollTop: $("#"+divId).offset().top
}, 2000);
}如果您认为它不起作用,那么尝试添加下面的css。它会造成按钮和你的div之间的差距。
#navButton {
height: 300px;
border:1px solid green;
}
#listContent {
height: 900px;
border: 1px solid red;
}https://stackoverflow.com/questions/35337894
复制相似问题