怎么用CSS或者JS实现鼠标点击变换背景图片?

html-css014

怎么用CSS或者JS实现鼠标点击变换背景图片?,第1张

<img src="1.jpg" width="100" height="100" alt="" onclick="pf(this)"/>

<script type="text/javascript">

var arr = ["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"]

function pf(t) {

t.src = arr[Math.floor(Math.random()*arr.length)]

}

script>

要CSS的呀?一般都用JS的。

如果是CSS的,只能做到背景切换,做不到图片本身切换。

为了要支持IE6,所以一般都用a的伪类来做这种效果

a{background-image:url(普通状态时的背景图片)}

a:hover{background-image:url(鼠标放上去的背景图片)}

如果是做图片本身切换的话,只能用JS

<img src="原图片" onmouseover="this.src='新图片'" onmouseout="this.src='原图片'" />

<div class="change">

</div>

<style>

.change {

animation: change 9s steps(1) infinite

background-repeat: no-repeat

background-position: center center

background-size: 100% auto

width: 200px

height: 100px

}

@keyframes change {

0% {

background-image: url(https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png)

}

33% {

background-image: url(https://www.duhongwei.site/img/201809/s1.png)

}

66% {

background-image: url(https://p4.ssl.qhimg.com/t01fcaa9d8a4d24b5f1.png)

}

}

</style>

纯 css 每3秒播一张图片。9s是总共时间,如果是4张图片这里写 12s