在通过getComputedStyle()方法获取ul li下面的img的宽度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!-- <link rel="stylesheet" href="fonts/iconfont.css"> -->
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 670px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
position: relative;
}
.box>ul {
list-style: none;
display: flex;
/* overflow: hidden; */
}
.box>p {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 100%;
display: flex;
justify-content: space-between;
}
.box>p>span {
width: 30px;
height: 60px;
background: rgba(0, 0, 0, .5);
color: #fff;
font-size: 40px;
line-height: 60px;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li>
<img src="images/ad1.jpg" alt="">
</li>
<li>
<img src="images/ad2.jpg" alt="">
</li>
<li>
<img src="images/ad3.jpg" alt="">
</li>
</ul>
<p>
<span class="left"><</span>
<span class="right">></span>
</p>
</div>
<script>
//1.拿到需要操作的元素
const oLeft = document.querySelector(".left");
const oRight = document.querySelector(".right");
const oUl = document.querySelector("ul");
const oItems = document.querySelectorAll("ul>li");
const imgWidth = parseFloat(getComputedStyle(oItems[0]).width);
console.log(imgWidth);//0
//2.
</script>
</body>
</html>
对于最终的结果不理解为什么为 0
补充:在IE11下能得到预期的结果 670,但是在谷歌浏览器下却是0
图片不应该在onload里面拿吗 图片还没加载 没宽度
1.你没给 img设置宽高 。
而且你获取 img 应该是 const oItems = document.querySelectorAll("ul>li>img");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!-- <link rel="stylesheet" href="fonts/iconfont.css"> -->
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 670px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
position: relative;
}
.box>ul {
list-style: none;
display: flex;
/* overflow: hidden; */
}
.box>p {
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 100%;
display: flex;
justify-content: space-between;
}
.box>p>span {
width: 30px;
height: 60px;
background: rgba(0, 0, 0, .5);
color: #fff;
font-size: 40px;
line-height: 60px;
}
img{
width: 500px;
}
</style>
</head>
<body>
<div class="box">
<ul>
<li>
<img src="https://ss1.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/baike/s%3d600%3bq%3d50/sign=c78810f334d12f2eca05ad607ff9a45f/8326cffc1e178a8205650e84f403738da977e8bd.jpg" alt="">
</li>
<li>
<img src="images/ad2.jpg" alt="">
</li>
<li>
<img src="images/ad3.jpg" alt="">
</li>
</ul>
<p>
<span class="left"><</span>
<span class="right">></span>
</p>
</div>
<script>
//1.拿到需要操作的元素
const oLeft = document.querySelector(".left");
const oRight = document.querySelector(".right");
const oUl = document.querySelector("ul");
const oItems = document.querySelectorAll("ul>li>img");
console.log(oItems[0].width);
//2.
</script>
</body>
</html>