【问题标题】:Smooth scrolling on button click单击按钮时平滑滚动
【发布时间】:2014-05-14 23:23:26
【问题描述】:

我使用了这个代码:

$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1000, 'swing', function () {
        window.location.hash = target;
    });
});

平滑滚动在链接和锚点之间完美运行!

但是我怎样才能让下面的按钮代码工作呢?

<input type="button" value="btn">

【问题讨论】:

  • 点击此按钮后,您希望如何定位任何特定元素?使用值属性还是什么?或者,您希望此按钮成为目标吗?还是您希望触发锚点点击事件?等等......你的问题很不清楚恕我直言

标签: javascript jquery button scroll smooth


【解决方案1】:

旧样式也可以使用:

<input type="button" value="btn" onclick="$('a[href^=\"#\"]').trigger('click')">

但你应该避免这种风格(内联事件)

【讨论】:

    【解决方案2】:

    你可以这样使用:

    $('input[type="button"][value="btn"]').on('click',function (e) {
    

    如果您需要两者都用逗号分隔:

    $('a[href^="#"], input[type="button"][value="btn"]').on('click',function (e) {
    

    但我强烈建议为它们使用公共类并像这样访问:

    $('.common_class').on('click',function (e) {
    

    【讨论】:

      【解决方案3】:

      你可以使用:

      $('input[type="button"]').on('click',function (e) {
      

      代替:

      $('a[href^="#"]').on('click',function (e) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        相关资源
        最近更新 更多