在html5页面中,一个div或者图片,鼠标移动上去的时候变大,移出的时候又变回原样怎么弄,

在html5页面中,一个div或者图片,鼠标移动上去的时候变大,移出的时候又变回原样怎么弄,,第1张

这里介绍两种方式:

一:通过css样式中的 ":hover"实现,代码如下

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

div{

background:red

width:200px

height:200px

}

div:hover{

background:red

width:500px

height:500px

}

</style>

</head>

<body>

<div>变大</div>

</body>

</html>

二:通过javascript方式实现,代码如下

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

div{

background:red

width:200px

height:200px

}

.divs{

background:red

width:500px

height:500px

}

</style>

</head>

<body>

<div>变大</div>

<script>

// 首先获取div元素

var divs = document.getElementsByTagName('div')[0]

//鼠标移入,将divs的className样式赋给该标签

divs.onmouseover = function () {

this.className = "divs"

}

//鼠标移出,将空的className样式赋给该标签

divs.onmouseout = function () {

this.className = ""

}

</script>

</body>

</html>

::before creates a pseudo-element that is the first child of the element matched. It is often used to add cosmetic content to an element by using the content property. This element is inline by default.

大概的意思:

::before创建了一个伪元素(跟伪造类类似,如:hover),位置在第一个子元素的位置,常用用于通过content属性来设置一些装饰性的内容;这个元素的属性默认是inline的。

::after也一样是伪元素,只不过位置是在子节点里面最后一个。

可以用定时器setInterval

如果是有限的背景色切换,那把这些颜色放在一个数组里面,一秒切换一次

1234567

var arrColor=['green','red','blue']var i=0setInterval(function(){obj.style.backgroundColor=arrColor[i] if(i==arrColor.length-1) i=0 i++},1000)

如果是随机变颜色,我这里写了一个随机颜色的方法

12345678910

function randomColor() {var Str=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']var color="#"for(var i=0i<6i++){var index=Math.ceil(Math.random()*Str.length)color+=Str[index]}return color}

你可以参考一下


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/7291004.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-03
下一篇2023-04-03

发表评论

登录后才能评论

评论列表(0条)

    保存