简体   繁体   English

单击后滚动到页面顶部

[英]It scrolls to the top of the page after clicking

I have this code to switch a switching button image: 我有以下代码来切换切换按钮图像:

$("#invio_scatola_on, #invio_scatola_off").click(function(){
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
});

when it is executed, the browser goes to the top of the page. 执行后,浏览器将转到页面顶部。 why? 为什么?

You probably need to prevent the default action of whatever element you click: 您可能需要防止单击任何元素的默认操作:

$("#invio_scatola_on, #invio_scatola_off").on('click', function(e){
    e.preventDefault();
    $("#invio_scatola_off, #invio_scatola_on").toggle();
});

Based on the few information that you've provided, if the browser is scrolling to the top, it means that you need to prevent its default behavior. 根据您提供的一些信息,如果浏览器滚动到顶部,则意味着您需要防止其默认行为。

Check to see if the browser is appending "something" to the current URL... 检查浏览器是否在当前URL 后面附加了 “某物” ...

You can prevent that like this: 您可以这样防止:

$("#invio_scatola_on, #invio_scatola_off").click(function(event){

  // prvent default behavior
  event.preventDefault();

  $("#invio_scatola_off").toggle();
  $("#invio_scatola_on").toggle();
});

See the jQuery event.preventDefault() for more information on how it works. 有关其工作方式的更多信息,请参见jQuery event.preventDefault()

I can only guess, because you didn't post your html code. 我只能猜测,因为您没有发布html代码。 Most probably your two elements are links with href="#" . 您的两个元素很可能是带有href="#"链接。 After you click handler the regular action is fired, navigating to the anchor # on your site (which is the top). 单击处理程序后,将触发常规操作,导航到站点上的锚点# (顶部)。

Try: 尝试:

$("#invio_scatola_on, #invio_scatola_off").click(function(event){
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
    event.preventDefault();
});

and see if that helps. 看看是否有帮助。 More on event cancelling with jQuery here: 有关使用jQuery取消事件的更多信息,请点击此处:

http://api.jquery.com/event.preventDefault/ http://api.jquery.com/event.preventDefault/

I think you binded the click on anchor tags with href as # so for that you can use preventDefault() of javascript like : 我认为您将带有href的 锚定标记的单击 绑定#,因此可以使用javascript的 preventDefault()

$("#invio_scatola_on, #invio_scatola_off").click(function(evt){
    evt.preventDefault();
    $("#invio_scatola_off").toggle();
    $("#invio_scatola_on").toggle();
});

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

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