我有5-10个链接,所有的链接都是同一个类/
<a class="content-link" href="/profile/about-me/<? echo $row['username'];?>/">我试图实现的是,当用户单击此链接时,用户将使用javascript导航到#profile-body div。
但是,与这个帖子非常相似的是,我希望用户在href中导航到的div,比如<a href="#profile-body">,我需要通过javascript来完成,因为我在href中的链接实际上是加载的。
预先感谢你所能提供的任何帮助。
发布于 2016-12-20 14:57:05
我知道您正在寻找Javascript解决方案,但是为了防止您愿意使用Jquery,这里有一个很好的解决方案。
$(document).ready(function() {
$('.content-link').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $('#profile-body').offset().top
}, 500);
});
});发布于 2016-12-20 15:19:36
这也可以用纯实现。
body {
background: #999
}
.mylinks a {
text-decoration: none;
color: black;
display: inline-block;
padding: 2%;
background: #444;
color: #999;
}
.mycooldiv {
background: red;
width: 100%;
height: 400px;
margin-bottom: 30%;
box-shadow: inset 0 0 10px 200px rgba(0, 0, 0, 0.55);
}
#profile-section1 {
background: red;
bottom: 100%
}
#profile-section2 {
background: blue;
bottom: 200%
}
#profile-section3 {
background: green;
bottom: 300%
}
#profile-section4 {
background: yellow;
bottom: 400%
}<body>
<div class="mylinks">
<a class="content-link" href="#profile-section1">section 1 </a>
<a class="content-link" href="#profile-section2">section 2 </a>
<a class="content-link" href="#profile-section3">section 3 </a>
<a class="content-link" href="#profile-section4">section 4 </a>
</div>
<div class="mycooldiv" id="profile-section1"></div>
<div class="mycooldiv" id="profile-section2"></div>
<div class="mycooldiv" id="profile-section3"></div>
<div class="mycooldiv" id="profile-section4"></div>
</body>
发布于 2016-12-20 14:59:50
但是,没有理由使用jQuery (除非您已经在使用它),这是一种完全普通的方法。设置散列是可选的。
基本上,这个脚本包含在新页面中,您可以手动设置散列,然后只需切换offsetTop。
(function() {
window.location.hash = "three";
document.getElementById('three').offsetTop + "px";
})();div {
height: 250px;
margin-bottom: 10px;
background-color: #F00;
}<div id='one'>one</div>
<div id='two'>two</div>
<div id='three'>three</div>
https://stackoverflow.com/questions/41245133
复制相似问题