[英]jQuery/Javascript - how do you prevent the currently clicked item from losing focus when another element offpage is updated
Suppose you have a div that is at the very top (usually offscreen, due to a long page) that is updated with .append()
when any of a bunch of links (scrolling also offpage) is clicked.假设您有一个位于最顶部的 div(通常是屏幕外,由于页面较长),当单击一堆链接(滚动也离页)中的任何一个时,它会使用.append()
进行更新。 How do you prevent Chrome from scrolling to the top automatically after each of the link clicks?每次点击链接后,如何防止 Chrome 自动滚动到顶部?
Something like this像这样的东西
<div id="updateme"></div>
<a href="#" onclick="DoAppendUpdateMe()"><img></a>
...
[hundreds more]
I strongly assume that Chrome doesn't scroll to the top because you are updating the content of the updateme
element, but because your link points to #
, which acts like an anchor on top of the page.我强烈假设 Chrome 不会滚动到顶部,因为您正在更新updateme
元素的内容,而是因为您的链接指向#
,它就像页面顶部的锚点一样。
Personally I'm not a big fan of using href="#"
, because it makes it possible to middle-click or Ctrl+click the link, opening it in a new tab, which is not an intended functionality.就我个人而言,我不是使用href="#"
的忠实拥护者,因为它可以中键单击或 Ctrl+单击链接,在新选项卡中打开它,这不是预期的功能。 I prefer using href="javascript:"
, but maybe there is an even better way that I don't know about.我更喜欢使用href="javascript:"
,但也许还有一种我不知道的更好的方法。
If you want to leave the link as it is, to prevent Chrome from scrolling up when clicking the link, you have to make sure that only the click handler is run when you click the link, and Chrome doesn't actually navigate to the href
you have specified, use onclick="event.preventDefault(); DoAppendUpdateMe()"
(see preventDefault ).如果您想保留链接原样,以防止 Chrome 在单击链接时向上滚动,您必须确保在单击链接时仅运行单击处理程序,并且 Chrome 不会实际导航到href
您已指定,请使用onclick="event.preventDefault(); DoAppendUpdateMe()"
(请参阅preventDefault )。
There are several ways to solve this, and it is because you are using an anchor hashtag (#).有几种方法可以解决这个问题,这是因为您使用的是锚标签 (#)。
<a href="#" onclick="DoAppendUpdateMe()"><img></a>
Instead, you could remove the href altogether but I am betting you want the style that href gives you.相反,您可以完全删除 href,但我打赌您想要 href 为您提供的样式。 I would recommend using css to style the a to look and act like a link (which is probably the cleanest method), but you can also do this if you like:我建议使用 css 将a设置为外观和行为类似于链接(这可能是最简洁的方法),但如果您愿意,也可以这样做:
<a href="javascript:void(0)" onclick="DoAppendUpdateMe()"><img></a>
This could also be covered with a little javascript when the page finishes loading as well if desired, since you listed jquery, it could be something like:如果需要,当页面完成加载时,这也可以用一点 javascript 覆盖,因为您列出了 jquery,它可能类似于:
$('a[href="#"]').on('click', function(e) {
e.preventDefault();
});
If going the above route, just in case these are dynamically loaded in, you might want something like:如果采用上述路线,以防万一这些是动态加载的,您可能需要以下内容:
$('#updateme').on('click', 'a[href="#"]', function(e) {
e.preventDefault();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.