
当鼠标指针悬停在上面时,改变 <p>元素的背景颜色:
$("p").hover(function(){
$("p").css("background-color","yellow")
},function(){
$("p").css("background-color","pink")
})
原生js里面可以用onmouseenter和onmouseleave实现。
如果一定要添加:hover伪类的话,就只能修改css样式了。。这个我查了好久还是不知道怎么办。
方法一,完全用js模拟(这样太麻烦)
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.css1{
width: 100px
height: 200px
border: 1px solid black
}
.css1:hover
{
border: 2px solid red
}
</style>
</head>
<body>
<div>这是一个div</div>
<script>
var div = document.getElementsByTagName("div")[0]
div.style.cssText = "border:1px solid redwidth:100pxheight:100px"
div.onmouseover = function () {
div.style.cssText = "border:1px solid blackwidth:100pxheight:100px"
}
div.onmouseout = function () {
div.style.cssText = "border:1px solid redwidth:100pxheight:100px"
}
</script>
</body>
</html>
2.方法二:js加css,还是麻烦
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.css1{
width: 100px
height: 200px
border: 1px solid black
}
.css1:hover
{
border: 2px solid red
}
</style>
</head>
<body>
<div>这是一个div</div>
<script>
// var div = document.getElementsByTagName("div")[0]
// div.style.cssText = "border:1px solid redwidth:100pxheight:100px"
// div.onmouseover = function () {
// div.style.cssText = "border:1px solid blackwidth:100pxheight:100px"
// }
// div.onmouseout = function () {
// div.style.cssText = "border:1px solid redwidth:100pxheight:100px"
// }
var div = document.getElementsByTagName("div")[0]
div.setAttribute("class","css1")
</script>
</body>
</html>
其实完全可以不用js来设置css,这样会比较麻烦,最直接的方法就是在元素里面直接设置class,在style或者css文件里面定义样式,如果有伪类这些也可以写在里面就好。
用js控制css伪类after:只能通过添加样式,然后通过这个样式的伪类来控制吧。。没法直接改。比如:
html:
<p>瓦赫塔 阿热 有 doing</p>
css:
p:after{
content:''
position:absolute
background-color:green
width:20px
height:6px
}
js:
var css=function(t,s){
s=document.createElement('style')
s.innerText=t
document.body.appendChlild(s)
}
document.onclick=function(){
css('p:after{background-color:red}')
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)