移动元素
- 1.我们怎么移动元素?
- 加一个li:让它相对于div偏移:加定位
- 效果图:
- 第二种方法:移动元素
- 效果图:
1.我们怎么移动元素?
1.给元素绝对定位,或相对定位 ,
position: relative; 有left和right.相对于
offsetLeft值:元素加了定位,看上一级的定位元素有关,是与
上一级的定位元素的偏移量。
如果:上一级定位元素是body,就是元素相对于body偏移量
在js中:有
div.style.left=div.offsetLeft+50+‘px’;//可以控制元素位置
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><style>div{
position: absolute;
left: 30px;width: 300px;height: 300px;background-color: pink;}
</style>
<body><div></div><button>1111</button><script>var div=document.querySelector("div");
var button=document.querySelector("button");
console.log(div.offsetLeft);button.οnclick=function(){div.style.left=div.offsetLeft+50+'px';console.log("我是");}</script></body>
</html>
点击:按钮元素移动了:offseLf:变化中
可以通过:div.style.left=div.offsetLeft+50+‘px’;
实现:元素移动
加一个li:让它相对于div偏移:加定位
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><style>div{
position: relative;/*加了定位,offsetLeft是相对于body偏移量*/
left: 30px;width: 300px;height: 300px;background-color: pink;}li{
position: relative;/*加了定位*/
width: 10px;
height: 10px;
background-color: brown;}
</style>
<body><div><li>11111111111</li></div><button>1111</button><script>var div=document.querySelector("div");
var button=document.querySelector("button");
var li=document.querySelector("li");
console.log(div.offsetLeft);button.οnclick=function(){div.style.left=div.offsetLeft+50+'px';
li.style.left=li.offsetLeft+10+'px';console.log(div.offsetLeft);
console.log("li的偏移量");
console.log(li.offsetLeft);}</script></body>
</html>
效果图:
这个可以应用:轮播图
第二种方法:移动元素
var index=0
div.style.left=(index*(100))+’%’;
index++;
父元素的变化,给left赋值为父元素的10%,100%
*li.style.left=(index10)+’%’;/ 相对于 /
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><style>div{
position: relative;/*加了定位,offsetLeft是相对于body偏移量*/
left: 30px;width: 300px;height: 300px;background-color: pink;}li{
position: relative;
width: 10px;
height: 10px;
background-color: brown;}
</style>
<body><div><li>11111111111</li></div><button>1111</button><script>var div=document.querySelector("div");
var button=document.querySelector("button");
var li=document.querySelector("li");
index=0;
console.log(div.offsetLeft);button.οnclick=function(){li.style.left=(index*10)+'%';/* 相对于 */console.log(li.style.left);
console.log("li的偏移量");
console.log(li.offsetLeft);
index++;}</script></body>
</html>