仅在第一个单选按钮上单击滚动页面

时间:2015-10-23 17:58:28

标签: javascript jquery css

点击了id =“yourgoal”的单选按钮后,我的页面显示了一个div。我希望页面只在第一次单击“yourgoal”中的按钮时滚动到该div。这是我正在使用的代码。我不希望页面在第一次点击后滚动到div。

$('input:radio[name="yourgoal"]').change(function() {
                 if ($('#calculations1').css('display') == 'none') {
                            $('html, body').animate({
                            scrollTop: $("#scrollto").offset().top
                            }, 1500);

                    }

问题是,它打破了我在.change()上的其余功能。我不希望将滚动后的所有函数放在if中,然后再将其放入else {}语句中,因为这似乎是一堆冗余代码(它也打破了它)?我如何只做一个简单的if语句,它不会影响.change函数中的其余动作?

也许有一个更简单的解决方案而且我在想这个?

提前致谢!

2 个答案:

答案 0 :(得分:2)

$('input:radio[name="yourgoal"]').one('change',
    function () {
        if ($('#calculations1').css('display') == 'none') {
            $('html, body').animate({
                scrollTop: $("#scrollto").offset().top
            }, 1500);
        }
    }
);

我建议使用一个。在第一次触发事件后,它会自动删除。

如果您在第一次更改后需要保留更多代码,则可以使用事件命名空间并附加多个更改。

$('input:radio[name="yourgoal"]').one('change.firstChange',
    function () {
        if ($('#calculations1').css('display') == 'none') {
            $('html, body').animate({
                scrollTop: $("#scrollto").offset().top
            }, 1500);
        }
    }
);
$('input:radio[name="yourgoal"]').on('change.allChanges',
    function () {
        // All your other code that stays attached
    }
);
编辑:似乎从那以后一个人都没有工作'一个'事件将附加到名称为yourgoal的每个单选按钮上,因此它将为每个第一个单选按钮单独单击滚动一次但如果您只想在第一次选择单选按钮时滚动而不是第一次选择时可以执行此操作所有共享你的名字的其他单选按钮。

小提琴:http://jsfiddle.net/31s3LLjL/3/

$('input:radio[name="yourgoal"]').on('change.firstChange',
    function () {
        $('input:radio[name="yourgoal"]').off('change.firstChange');
        $('html, body').animate({
            scrollTop: $("#scrollto").offset().top
        }, 1500);
    }
);
$('input:radio[name="yourgoal"]').on('change.allChanges',
    function () {
        // Other change stuff
    }
);

答案 1 :(得分:0)

您可以使用event.stopImmediatePropagation()来阻止在特定事件上执行订阅的回调。

$('input:radio[name="yourgoal"]').one('change',function(event) {
  event.stopImmediatePropagation();
  if ($('#calculations1').css('display') == 'none') {
    $('html, body').animate({
      scrollTop: $("#scrollto").offset().top
    }, 1500);
  }
});

请确保您的代码预先包含所有其他change处理程序定义。