单击id =“ yourgoal”中的单选按钮后,我的页面显示div。我希望页面仅在第一次单击“您的目标”中的按钮时滚动到该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函数中其余的动作?
也许有一个更简单的解决方案,而我对此却认为过高?
提前致谢!
$('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
}
);
编辑:似乎一个将不起作用,因为该“ one”事件将附加到名称为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
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句