英文:
Enabling an anchor link to work with the spacebar
问题
我有一个返回顶部的链接,它跳转到页面上一个手风琴元素的顶部锚点链接处 - 我已经将其设置为可访问的按钮,并且使用鼠标点击它时效果正常,但是按下空格键没有预期的结果,只是向下滚动页面。
我的JS代码用于处理锚点和重新设置焦点:
jQuery(function($){
$("#back-to-top-2").on("click", function () {
$("html, body").animate({scrollTop: $("#top2").offset().top}, 500);
$("#et_pb_accordion_1").focus();
});
});
如何使空格键的函数调用与点击事件的行为相同?
英文:
I have a back-to-top link that jumps to an anchor link on the page at the top of an accordion element - I have it working as a button for accessibility and clicking on it with the mouse works as expected but the space bar doesn't have the desired result and just scrolls down the page.
My JS for the anchor and setting the focus again is:
jQuery(function($){
$("#back-to-top-2").on("click", function () {
$("html, body").animate({scrollTop: $("top2").offset().top}, 500);
$("#et_pb_accordion_1").focus();
});
});
How do I get the spacebar to the function call to act the same way as the on-click?
答案1
得分: 1
你需要监听元素上的keydown事件,并检查是否按下了空格键(键码32)。
尝试这样做:
jQuery(function($) {
$("#back-to-top-2").on("click keydown", function (event) {
if (event.type === "click" || (event.type === "keydown" && event.keyCode === 32)) {
if (event.type === "keydown") {
event.preventDefault(); // 阻止默认的空格键滚动行为
}
$("html, body").animate({scrollTop: $("#top2").offset().top}, 500);
$("#et_pb_accordion_1").focus();
}
});
});
英文:
you need to listen for the keydown event on the element and check if the spacebar key (key code 32) was pressed.
try this:
jQuery(function($) {
$("#back-to-top-2").on("click keydown", function (event) {
if (event.type === "click" || (event.type === "keydown" && event.keyCode === 32)) {
if (event.type === "keydown") {
event.preventDefault(); // Prevent default spacebar scrolling behavior
}
$("html, body").animate({scrollTop: $("#top2").offset().top}, 500);
$("#et_pb_accordion_1").focus();
}
});
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论