没有关于鼠标焦点的轮廓,但仍然有关于键盘焦点的轮廓? [英] No outline on mouse focus but still have outline on keyboard focus?

查看:192
本文介绍了没有关于鼠标焦点的轮廓,但仍然有关于键盘焦点的轮廓?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当页面的元素具有焦点时(例如链接或按钮),它们将显示一个大纲。我希望这个轮廓仅在该元素通过键盘而不是鼠标获得焦点时显示。



是否有可能确定该元素如何获得焦点JavaScript的?如果是这样,那么我该如何控制浏览器自身的大纲功能? 浏览器使用CSS 大纲属性显示哪个元素具有焦点,正如您可能已经知道的那样。因此,在jQuery中,您可以使用:

  $(document).ready(function(){
$( ($(this).is(:focus)|| $(this).is(e。)(body)。on(mousedown,*,function目标))&& $(this).css(outline-style)==none){
$(this).css(outline,none)。on ();
$(this).off(blur).css( );
});

解释:此函数查找 mousedown任何元素上的事件。此事件是委托,这意味着它将应用于页面上的当前元素以及将来动态创建的元素。当鼠标点击元素时,其CSS outline 属性设置为 none ;

目标元素为 blur 获取一个新的处理程序。当从元素中获取焦点时, outline 属性设置为空字符串(这会将其从元素的样式属性),允许浏览器再次控制轮廓。然后,元素删除自己的 blur 处理程序以释放内存。这样,一个元素只能在从键盘聚焦时被勾勒出来。



编辑



根据下面的Rakesh的评论,我做了一个小小的改变。该函数现在可以检测是否已经存在 outline set,并且可以避免覆盖它。 此处演示


When elements of a page have focus (such as a link or button), they show an outline. I would like this outline to only display when that element was given focus by the keyboard, not by the mouse.

Is it possible to determine how that element got its focus with JavaScript? If so, how do I then control the browser's own outlining feature?

解决方案

Browsers use the CSS outline property to show which element has the focus, as you might already know. So, in jQuery, you might use:

$(document).ready(function() {
    $("body").on("mousedown", "*", function(e) {
        if (($(this).is(":focus") || $(this).is(e.target)) && $(this).css("outline-style") == "none") {
            $(this).css("outline", "none").on("blur", function() {
                $(this).off("blur").css("outline", "");
            });
        }
    });
});

Explanation: This function looks for the mousedown event on any element. This event is delegated, meaning it will apply to elements currently on the page as well as any created dynamically in the future. When the mouse is clicked over the element, its CSS outline property is set to none; the outline is removed.

The targeted element gets a new handler for blur. When focus is taken from the element, the outline property is set to a blank string (this removes it from the element's style attribute), allowing the browser to control the outline again. Then, the element removes its own blur handler to free up memory. This way, an element is only outlined when focused from the keyboard.

Edit

Based on Rakesh's comments below, I made a slight change. The function can now detect if there's already an outline set, and will avoid overriding it. Demo here.

这篇关于没有关于鼠标焦点的轮廓,但仍然有关于键盘焦点的轮廓?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆