【问题标题】:scroll window on click jquery?单击jquery时滚动窗口?
【发布时间】:2017-11-19 00:46:46
【问题描述】:

准确地说,我需要在单击按钮时将窗口滚动到div 的顶部。

我试过了:

$(".red").animate({"scrollTop": $(".red").scrollTop()},1000);

但是没用

看看这个 jsfiddle:https://jsfiddle.net/gu8gx1ad/3/

【问题讨论】:

标签: jquery


【解决方案1】:

你必须滚动 html,body 像你的元素一样

$("html,body").animate({"scrollTop": $(".red").offset().top},1000);

片段,

function sc(w) {
  var cls = '';
  switch (w) {
    case 0:
      cls = '.green';
      break;
    case 1:
      cls = '.blue';
      break;
    case 2:
      cls = '.red';
      break;
  }
  cls && $("html,body").animate({
    "scrollTop": $(cls).offset().top
  }, 1000);

}
.green,
.red,
.blue {
  height: 200px;
  width: 300px;
  background: green;
  margin-top: 100px;
}
.red {
  background: red;
}
.blue {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#green" style="color:green;" onclick="sc(0)">green</a>
<a href="#blue" style="color:blue;" onclick="sc(1)">blue</a>
<a href="#red" style="color:red;" onclick="sc(2)">red</a>
<div class="green"></div>
<div class="blue"></div>
<div class="red"></div>

【讨论】:

    【解决方案2】:

    以下代码应该可以为您解决问题。但它只有在相应的部分有他们的 ID 名称而不是类名之后才有效:

    <a href="#green" style="color:green;" onclick="sc(0)">green</a>
    <a href="#blue" style="color:blue;" onclick="sc(1)">blue</a>
    <a href="#red" style="color:red;" onclick="sc(2)">red</a>
    <div id="green" ></div>
    <div id="blue" ></div>
    <div id="red" ></div>
    
    
    
        $('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').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
            }
        });
    

    【讨论】:

      【解决方案3】:

      我不确定您为什么要尝试使用 JQuery 来执行此操作。您需要做的就是为潜水提供一个 ID 并在您的链接中引用该 ID,如下所示。

      <a href="www.domain.com/#red">GoToRed</a>
      
      <div id="red">
          div content
      </div>
      

      【讨论】:

      • 虽然这更简单,但它不会像 jQuery 版本那样为向下滚动的页面设置动画。这可能是 OP 的要求。另外,仅供参考,反对票不是我的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多