繁体   English   中英

jQuery结合了2个脚本以实现平滑滚动以定位

[英]jQuery combine 2 scripts to achieve smooth scrolling to anchor

我有以下jquery函数,根据选择的div显示/隐藏内容...

jQuery(document).ready(function() {
  jQuery('.showSingle').on('click', function () {
    jQuery(this).addClass('selected').siblings().removeClass('selected');
    jQuery('.targetDiv').hide();
    var selector = '#div' + jQuery(this).data('target');
    jQuery(selector).show();
    location.hash = selector;
  });
});

http://jsfiddle.net/W4Km8/7944/

我也从http://1stwebmagazine.com/jquery-scroll-to-anchor-point提取了以下脚本

$(document).ready(function(){
    $('a[href^="#"]').bind('click.smoothscroll',function (e) {
        e.preventDefault();

        var target = this.hash,
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top-40
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

我正在尝试结合2,以便滚动到它而不是跳转到锚点。 我需要将它们组合在一起还是可以使其分开工作?

看起来您可以轻松地将它们组合在一起,我已经使其与以下jsfiddle一起使用: http : //jsfiddle.net/9soxbhpj/

var target = jQuery(selector);
target.show()
$('html, body').stop().animate({
        'scrollTop': target.offset().top-40
    }, 900, 'swing', function () {
        window.location.hash = selector;
    });

您可以在同一点击调用中添加滚动操作。 看到j​​s:

jQuery(document).ready(function() {

  jQuery('.showSingle').on('click', function () {
    var _el = jQuery(this),
        _target =  jQuery('#div' + _el.data('target')),
        _targetDiv = jQuery('.targetDiv');

    _el.addClass('selected').siblings().removeClass('selected');
    _targetDiv.hide();
    _target.show();

    // Scroll to object
    $('html, body').animate({
        scrollTop: _target.offset().top
    }, 800);

  });

});

这是一个工作示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM