这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.A:focus-visible {
outline: none;
}
</style>
</head>
<body>
<div contentEditable="true" class="A"></div>
</body>
</html>
这是用CSS实现的。我希望用JS实现。
测试代码如下
<!doctype html>
<title>javascipt修改css级联样式表类和伪类样式</title>
<style>
.exampleA{color:Blue}
.exampleA:before {content:"-";color:red;font-size:20px;font-weight:bold}
</style><!--IE条件注释,判断是否IE8浏览器-->
<!--[if IE 8]><script>var IE8=true</script><![endif]-->
<script>
function changecss(theClass, element, value) {
var sl = document.styleSheets.length;
if (sl == 0) return;
var isPseudo = theClass.indexOf(':') != -1;//css伪类
//非IE8-,js获取到伪类名称包含二个冒号
if (window.IE8) theClass = theClass.replace(/:+/g, ':');
else theClass = theClass.replace(/:+/g, '::');
var cssRules = document.styleSheets[0].rules ? 'rules' : 'cssRules';
for (var i = 0; i < sl; i++) {
for (var j = 0, rl = document.styleSheets[i][cssRules].length; j < rl; j++) {
if (document.styleSheets[i][cssRules][j].selectorText == theClass) {
if (isPseudo) //css伪类需要覆盖,替换值没用
document.styleSheets[i].addRule ?
document.styleSheets[i].addRule(theClass, element + ':' + value) ://IE8+,chrome
document.styleSheets[i].insertRule(theClass + '{' + element + ':' + value + '}', rl);//firefox
else document.styleSheets[i][cssRules][j].style[element] = value;
break;
}
}
}
}
</script>
<span class="exampleA">Example A</span><br />
<span class="exampleB">Example B</span><br />
<span class="exampleA">Example A</span><br />
<input type="button" value="修改exampleA为红色" onclick="changecss('.exampleA','color','red')"/>
<input type="button" value="修改exampleA为黑色" onclick="changecss('.exampleA','color','black')" />
<input type="button" value="修改exampleA:before伪类color为blue" onclick="changecss('.exampleA::before','color','blue')" />
<input type="button" value="修改exampleA:before伪类color为red" onclick="changecss('.exampleA::before','color','red')" />
这有啥难的?你只要通过js给指定的div或者某一个指定标签添加css不就行了,代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div contentEditable="true"></div>
</body>
<script>
var obj = document.getElementById("div");
obj.css("div:focus-visible='outline: none'")
</script>
</html>
给DIV设置属性ID,参考:
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>上面的段落已被脚本改变。</p>
</body>
</html>