Joh*_*ohn 36 html javascript css jquery html5
我想创建一个链接,并使用javaScript强制链接锚点,我尝试了以下内容: -
<a id="ServerSort" href="#" style="text-decoration:underline">
Run Code Online (Sandbox Code Playgroud)
它运作良好,但点击<a>链接后页面将失去当前位置.
我需要链接有一个href,因为我需要鼠标来更改光标吗?
谁有人建议?
Tus*_*har 41
您可以使用 javascript:void(0)
<a id="ServerSort" href="javascript:void(0)">
Run Code Online (Sandbox Code Playgroud)
你不需要King King的style="text-decoration:underline"评论
停止事件的默认操作.
$('#ServerSort').click(function(event){
event.preventDefault(); //or return false;
});
Run Code Online (Sandbox Code Playgroud)
Ben*_*ene 21
最好的方法是将href设置为#0这样:
<a href="#0">blabla</a>Run Code Online (Sandbox Code Playgroud)
原因如下:你永远不会在ID为0的页面上有任何东西(如果你这样做,反正存在问题),并且由于#0不存在,click事件不会让你回到页面顶部.您不需要JavaScript来执行此操作,也不应使用JavaScript.
.clickable {
cursor: pointer;
}Run Code Online (Sandbox Code Playgroud)
<a id="ServerSort" class="clickable">Foo</a>Run Code Online (Sandbox Code Playgroud)
此方法告诉用户代理,如果事件没有得到显式处理,则不应像通常那样采取其默认操作。
function clickme(ev) {
alert('You stay here!')
ev.preventDefault()
}Run Code Online (Sandbox Code Playgroud)
<a onclick='clickme(event)' href='https://www.google.com/'>https://www.google.com</a>Run Code Online (Sandbox Code Playgroud)
事件继续照常传播,除非其事件侦听器之一调用
stopPropagation()或stopImmediatePropagation(),其中任一事件立即终止传播。
或者,您可以使用onclick='return false'(内联或在函数中)。它将阻止默认浏览器行为(更多信息):
function clickme() {
alert('You stay here!');
return false;
}Run Code Online (Sandbox Code Playgroud)
<a href="https://www.google.com/" onclick='return clickme()'>https://www.google.com/</a>Run Code Online (Sandbox Code Playgroud)
不过,这种方法可以防止事件传播。更多细节。
存在几个选项:
<a id="ServerSort" href="javascript:">
<a id="ServerSort" href="javascript://">
<a id="ServerSort" href="javascript:void(0)">
Run Code Online (Sandbox Code Playgroud)
这些被认为是不好的做法,我永远不会推荐这样的东西用于生产。当链接到开发阶段不存在的页面时,我通常使用第一个选项。
最好,我根本不会使用 a,我在下面的示例中切换到一个跨度:
<span id="ServerSort" onclick="return false">Test Link</span>
Run Code Online (Sandbox Code Playgroud)
并相应地设置元素的样式:
<style type="text/css">
#ServerSort {
text-decoration:underline;
}
#ServerSort:hover {
color:red;
cursor:pointer;
}
</style>
Run Code Online (Sandbox Code Playgroud)
我正在内嵌 js,只是在这里手写一个来展示一种不同的方法,它避免了覆盖默认行为的需要。
| 归档时间: |
|
| 查看次数: |
50804 次 |
| 最近记录: |