Javascript通过点击元素添加通用选择器CSS规则-或者更新通用选择器规则以具有类名



如果我们可以突出显示导致水平滚动的元素,那么在移动设备上调试UI会变得更容易-这可以通过使用通用选择器的CSS行轻松完成:

* { border: 1px solid #f00 !important; }

工作很好,但要打开和关闭它,我们需要重新编译sass,或者跳出我们定义的过程。。。或者找到一个不错的JS解决方案。

我们有一个方便的BootStrap断点查看器,在其中添加一个点击操作以应用CSS规则On/Off是有意义的,这样我们可以节省一些时间,并为UI开发人员提供良好的用户体验。。

所以,第一个go工作不好,我们不能使用addClass,然后使用removeClass,因为选择器没有命名。。

此外,我们已经尝试了以下几种变体来全局应用于css规则,但它们还不起作用:

// click to add debug borders ##
jQuery('#bs_helper').click(function(e){
// console.log( 'Clicked BS..' );
jQuery( document ).find("*").css( "border", "1px solid #f00 !important" );
});

此外,不适用于:

jQuery( "*" ).css( "border", "1px solid #f00 !important" );

有什么提示吗?我们需要单击一次来添加,再单击一次以删除规则。

谢谢!

更新-这是有效的,但也许还有更好的方法?

var $bs_helper_css = false;
// click to add debug borders ##
jQuery('#bs_helper').click(function(e){
if( ! $bs_helper_css ) {
var html = "<style id='bs_helper_css'>* { border: 1px solid #f00 !important; }</style>";
console.log( 'Add: '+html );
jQuery('body').append(html); 
// tracker ##
$bs_helper_css = true;
} else {
console.log( 'Remove CSS' );
jQuery('#bs_helper_css').remove();
// tracker ##
$bs_helper_css = false;
}
return true;
});

您可以在body上添加/删除类

body.debug * { border: 1px dashed pink; }

作为奖励,如果需要,您还可以排除项目(如调试按钮(:

$("#debug").click(function() { $("body").toggleClass("debug"); });
body.debug :not(.nodebug) { border: 1px dashed pink; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div>basic element</div>
<div><div>nested element</div></div>
<hr class='nodebug' />
<button type='button' id='debug' class='nodebug'>debug</button>
</body>

最新更新