首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iWeb iFrames和平滑滚动问题

iWeb iFrames和平滑滚动问题
EN

Stack Overflow用户
提问于 2016-09-16 10:46:07
回答 2查看 382关注 0票数 0

我正在使用iWeb (很可怕,但我必须使用它,说来话长)。

我已经设法在一个页面上获得一些平滑的滚动链接,但我有困难让它滚动到正确的位置。

下面是加载到iframe中的“”代码(FYI,这是菜单):

代码语言:javascript
复制
<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。

我怎样才能让它像我所需要的那样工作,而不对每个链接重复复制/粘贴相同的功能呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-16 10:58:44

我建议使用一种字典来将链接散列映射到元素ID:

代码语言:javascript
复制
var map = {
    '#about':     'id1',
    '#products':  'id4',
    '#technical': 'id7',
    '#contactus': 'id14',
};

这样,您就可以使用target作为映射的密钥:

代码语言:javascript
复制
if (target.length && target in map) {
    $('html, body', window.parent.document).animate({
        scrollTop: parent.document.getElementById(map[target]).offsetTop,
    }, 1000);
    return false;
}
票数 0
EN

Stack Overflow用户

发布于 2016-09-16 11:51:38

这太棒了,一开始它不太好用,但是下面是我用来让它完全按照预期工作的代码:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39529587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档