js 图片居中
时间: 2023-08-06 08:16:18 浏览: 84
在JavaScript中,可以通过获取图片的宽度和高度,以及其父元素的宽度和高度,来实现图片的居中显示。
具体实现方法如下:
1. 获取图片的宽度和高度,可以使用JavaScript中的`naturalWidth`和`naturalHeight`属性。
2. 获取图片的父元素的宽度和高度,可以使用JavaScript中的`clientWidth`和`clientHeight`属性。
3. 计算出图片需要移动的距离,通过设置图片的`margin-top`和`margin-left`属性来使其居中显示。
下面是示例代码:
```
<style>
.container {
width: 400px;
height: 300px;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
}
.container img {
max-width: 100%;
max-height: 100%;
}
</style>
<div class="container">
<img src="example.jpg" alt="示例图片">
</div>
<script>
var img = document.querySelector('.container img');
var container = document.querySelector('.container');
var offsetTop = (container.clientHeight - img.naturalHeight) / 2;
var offsetLeft = (container.clientWidth - img.naturalWidth) / 2;
img.style.marginTop = offsetTop + 'px';
img.style.marginLeft = offsetLeft + 'px';
</script>
```
通过以上步骤,就可以实现图片在父元素中居中显示了。其中,父元素的宽度和高度需要根据实际情况进行调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)