我有三个选项可以阻止视图被推到页面顶部:
href="#!"
href="javascript:;"
示例:
$('#lang1_special_chars').on("click", ".lang1_char", function(e){
e.preventDefault();
// Rest of the code
});
感谢@ [Scott Brown]和@Barmar
我使用以下脚本将一个或多个字符添加到输入字段。不幸的是,在成功添加角色后,该功能使视图跳转到窗口的顶部。焦点停留在输入字段上。
观点位置应保持且不得移动。我使用了这个问题的代码:inserting a text where cursor is using Javascript/jquery。焦点必须留在输入字段上。
我的功能(已复制):
function insertAtCaret(areaId,text, jumpTo) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false ) );
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
range.moveStart ('character', strPos);
range.moveEnd ('character', 0);
range.select();
}
else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
这就是我调用函数的方式:
$('#lang1_special_chars').on("click", ".lang1_char", function(){
var text = $(this).data('char');
insertAtCaret('word_lang1', text);
});
这是html代码:
<div class="input-field">
<input type="text" id="word_lang1" placeholder="Pal" required="" class="validate" tabindex="1">
<label for="word_lang1" class="active">Deutsch</label>
<div id="lang1_special_chars">
<a href="#" class="lang1_char" data-char="Ä">
<div class="chip orange lighten-2">Ä</div>
</a>
<a href="#" class="lang1_char" data-char="ä">
<div class="chip orange lighten-2">ä</div>
</a>
<a href="#" class="lang1_char" data-char="Ö">
<div class="chip orange lighten-2">Ö</div>
</a>
<a href="#" class="lang1_char" data-char="ö">
<div class="chip orange lighten-2">ö</div>
</a>
<a href="#" class="lang1_char" data-char="Ü">
<div class="chip orange lighten-2">Ü</div>
</a>
<a href="#" class="lang1_char" data-char="ü">
<div class="chip orange lighten-2">ü</div>
</a>
<a href="#" class="lang1_char" data-char="ß">
<div class="chip orange lighten-2">ß</div>
</a>
</div>
</div>
谢谢!
答案 0 :(得分:4)
可能是因为您在href="#"
代码中调用了a
。将其更改为href="javascript:;"
。这将阻止它尝试跳转到任何命名锚点。
答案 1 :(得分:1)
通过调用event.preventDefault();
更改处理程序以禁用关注链接的默认操作。
$('#lang1_special_chars').on("click", ".lang1_char", function(e){
e.preventDefault();
var text = $(this).data('char');
insertAtCaret('word_lang1', text);
});