[英]position a border around focused element
我希望聚焦的元素(通常使用Tab键导航)与元素大小的周围矩形一起显示。 我在html中创建了适当的div,并使用了适当的CSS作为边框颜色,并且在导航开始时不显示任何内容。 我正在尝试使用jquery(大小和位置)更改显示,但是出了点问题。
jQuery('*').focus(function () {
var position = jQuery(this).offset();
var width = jQuery(this).width();
var height = jQuery(this).height();
console.log(jQuery(this).width(), jQuery(this).height(), position);
jQuery('#focuser').fadeOut(0); //to have the div disappear if it is on other element
jQuery('#focuser').css({width: '2px', height: '2px'}); //to get an enlarging effect
jQuery('#focuser').offset({top: position.top, left: position.left});
jQuery('#focuser').fadeIn(100, function () {
jQuery('#focuser').animate({width: width, height: height}, 200);
});
console.log(jQuery('#focuser').width(), jQuery('#focuser').height(), jQuery('#focuser').offset());
});
jQuery(this)的位置检索是正确的,但是当我将其设置为offset时,似乎添加了该值而不是替换了它。 我想念什么吗? 这是管理它的正确方法(带有伪元素:focus的完整CSS解决方案不起作用,因为将边框添加到元素大小并破坏了页面显示,边框需要具有动画效果)?
#focuser {
border: 2px $second-font-color solid;
display: none;
position: absolute;
}
谢谢你的帮助
我想我找到了解决方案,但我不明白为什么会这样。 我将淡出置于变量设置之前,它看起来可以工作。
jQuery('*').focus(function () {
jQuery('#focuser').fadeOut(0);
var position = jQuery(this).offset();
var width = jQuery(this).width();
var height = jQuery(this).height();
jQuery('#focuser').fadeIn(0);
jQuery('#focuser').css({width: 0, height: 0});
jQuery('#focuser').offset({top: position.top, left: position.left});
jQuery('#focuser').animate({width: width, height: height}, 200);
});
您可以使用基本的css :focus
选择器,而无需使用JQuery。 有关更多信息,请参见W3Schools 。
在对元素进行聚焦之前,您需要为其提供相同大小的边框,并且可以为其提供与背景相同的颜色。 否则边境将采取额外的空间和摧毁你的布局说明这里 。 您还可以将页margin
设置为2px
,并在焦点2px
项目时将其删除,这样它仍会放大。
检查此小提琴以了解我的意思: jsfiddle.net/GillesCoeman/30vhjtdh/3 。 它还使用CSS transition
来添加效果。
如果这不是您要找的东西,也可以使用this和jQuery的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.