JavaScript之点击改变图片形状(transform的应用),供大家参考,具体内容如下
附上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>transform的运用</title>
<style type="text/css">
#box{
width: 50px;
height: 50px;
background-color: red;
/*traslate 位移 rotate 旋转幅度 scale 放大幅度 skew倾斜*/
/*transform: translate(100px,200px) rotate(20deg) scale(2.0) skew(10deg);*/
}
</style>
</head>
<body>
<button id="btn">形变</button>
<div id="box"></div>
<script>
window.onload = function (){
var btn = document.getElementById("btn");
var box = document.getElementById("box");
var index = 0;
btn.onclick = function (){
index++;
box.style.transform = `translate(${index*100}px,${index*50}px) rotate(${index*10}deg) scale(${index*1.3})`;
}
}
</script>
</body>
</html>
实现效果图:
默认原始情况下:
点击形变后:
再次点击则会继续发生变化。
下边对transform的应用进行扩展,运用于时钟的走动:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数字时钟案例</title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
#clock{
width: 600px;
height: 600px;
background: url("img/clock.jpg") no-repeat;
position: relative;
}
#hour,#minute,#second{
position: absolute;
width: 30px;
height: 600px;
left: 50%;
margin-left: -15px;
}
#hour{
background: url("img/hour.png") no-repeat;
}
#minute{
background: url("img/minute.png") no-repeat;
}
#second{
background: url("img/second.png") no-repeat;
}
</style>
</head>
<body>
<div id="clock">
<div id="hour"></div>
<div id="minute"></div>
<div id="second"></div>
</div>
<script type="text/javascript">
// 1.获取标签
var hour = document.getElementById("hour");
var minute = document.getElementById("minute");
var second = document.getElementById("second");
// 2.开启定时器 获取当前时间
setInterval(function (){
// 2.1获取当前的时间戳
var now = new Date();
// 2.2获取小时 分钟 秒
var s = now.getSeconds();
var m = now.getMinutes() + s/60;
var h = now.getHours()%12 + m/60;
// 2.3旋转
second.style.transform = `rotate(${s*6}deg)`;
minute.style.transform = `rotate(${m*6}deg)`;
hour.style.transform = `rotate(${h*30}deg)`;
},10)
</script>
</body>
</html>
附上效果图(现在是八点零一):