启用锚链接与空格键一起使用

huangapple go评论66阅读模式
英文:

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();
    }
    });
});

huangapple
  • 本文由 发表于 2023年8月8日 22:49:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定