我正在使用iWeb (很可怕,但我必须使用它,说来话长)。
我已经设法在一个页面上获得一些平滑的滚动链接,但我有困难让它滚动到正确的位置。
下面是加载到iframe中的“”代码(FYI,这是菜单):
<html>
<head>
<script type="text/javascript">
// the var's are referneces to iWeb's generated div's have to publish and get id's
var about = "id1";
var products = "id4";
var technical = "id7";
// var contactus = "id14";
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body', window.parent.document).animate({
//scrollTop: parent.document.getElementById(products).offsetTop // this works but is a static ref
scrollTop: parent.document.getElementById(theTarget).offsetTop
}, 1000);
return false;
}
}
});
});
</script>
</head>
<body>
<div style="width: "100%"; height: "0%"">
<a href="#about" id="about" class="myButton">About</a>
<a href="#products" id="products" class="myButton">Products</a>
<a href="#technical" id="technical" class="myButton">Technical</a>
<a href="#contactus" id="contactus" class="myButton">Contact</a>
</div>
</body>
</html>现在,当我看到这个点击链接时,它只会加载iframe页面,而不是滚动主窗口。
但是,如果我注释/取消注释另一个ScrollTop行,它将工作,但显然它只会滚动到父窗口中的"id4“div。
我怎样才能让它像我所需要的那样工作,而不对每个链接重复复制/粘贴相同的功能呢?
发布于 2016-09-16 10:58:44
我建议使用一种字典来将链接散列映射到元素ID:
var map = {
'#about': 'id1',
'#products': 'id4',
'#technical': 'id7',
'#contactus': 'id14',
};这样,您就可以使用target作为映射的密钥:
if (target.length && target in map) {
$('html, body', window.parent.document).animate({
scrollTop: parent.document.getElementById(map[target]).offsetTop,
}, 1000);
return false;
}发布于 2016-09-16 11:51:38
这太棒了,一开始它不太好用,但是下面是我用来让它完全按照预期工作的代码:
<script type="text/javascript">
var map = {
'about': 'id1',
'products': 'id4',
'technical': 'id7',
'contactus': 'id11',
};
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
$('html, body', window.parent.document).animate({
scrollTop: parent.document.getElementById(map[this.hash.slice(1)]).offsetTop
}, 1000);
return false;
}
}
});
});
</script>https://stackoverflow.com/questions/39529587
复制相似问题