[英].focus() not working while inside .on('click', function(event)
單擊鏈接時,我使用以下功能將頁面滾動到特定元素,效果很好:
$('a.scroll-link').on('click', function(event) {
var target = $(this).attr('href')
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 800);
}
});
我正在嘗試添加一個focus()事件以專注於整個表單元素。 它不起作用,我不知道為什么。 我嘗試了以下代碼的幾種變體:
$('a.scroll-link').on('click', function(event) {
var target = $(this).attr('href')
if (target.length) {
event.preventDefault();
$('#mainForm').focus();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 800);
}
});
變體2:
$('a.scroll-link').on('click', function(event) {
$('#mainForm').focus();
var target = $(this).attr('href')
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 800);
}
});
#3與超時:
$('a.scroll-link').on('click', function(event) {
var target = $(this).attr('href')
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 800);
setTimeout(function() { $('#mainForm').focus() }, 3000);
}
});
他們都不工作。 僅供參考,我將focus()更改為addClass()函數,並且效果很好。 但是焦點是更可取的,因為當選擇單個輸入時它會消失。 當輸入集中時,我寧願不必編寫另一個函數來刪除該類。 非常感謝。
您確定.focus()
用於聚焦表單嗎? 在大多數情況下,焦點將在一個輸入字段上用於用戶輸入,您應該以該形式選擇輸入字段,但不能全部選擇。
您能否參考此鏈接,這是單擊功能內部使用的代碼
$( "#other" ).click(function() {
$( "#target" ).focus();
});
所以我實際上是自己想出來的。 它與jQuery代碼無關,而與HTML無關。 為了使.focus()
對<form>
類的元素起作用,需要將tabindex
值設置為可聚焦。 所以我更新了html使其看起來像這樣:
<form name="mainForm" id="mainForm" tabindex="-1">
添加tabindex
值使其起作用。 萬一有人在意,我在jQuery代碼中使用了以下內容,以便頁面滾動發生在焦點之前。 否則,頁面在首先聚焦時將移動到表單的底部,然后向上滾動到表單的開頭:
$('a.slide-down').on('click', function(event) {
var target = $(this).attr('href')
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: $(target).offset().top
}, 800);
$('#mainForm').focus();
}
});
謝謝大家的其他建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.