javascript - div的CSS边框半径:首次加载时伪元素渲染错误
问题描述
我一直在尝试通过使用具有匹配边框半径的 div:after 伪元素来更改图像颜色叠加层。
https://jsbin.com/konopak/1/edit?html,输出
您会注意到在第一次加载时背景颜色是一个实心正方形,但如果您移动框架或更改页面上的任何元素,它会正确呈现它。有没有办法让它在第一次加载时正确渲染?为什么会这样?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
img {
max-width: 100%;
height: auto;
border-radius: 90px;
}
.hero-image {
position: relative;
max-width: 200px;
display: flex;
background-color: #ff000050;
/* border-radius: 90px; */
}
.hero-image:after {
position: absolute;
height: 100%;
width: 100%;
background-color: inherit;
top: 0;
left: 0;
display: block;
content: "";
border-radius: 90px;
}
</style>
</head>
<body>
<label id="color-label" style="background-color: #ff0000; height: 18px; width: 18px; border-radius: 10px; cursor: crosshair;">
<input id="color-tag" type="color" value="#ff0000" style="visibility: hidden;">
</label>
<div class="hero-image">
<img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=400&w=400" id="cat" alt=""/>
</div>
<script>
const label = document.getElementById('color-label');
document.getElementById('color-tag').addEventListener('change', function () {
label.style.backgroundColor = this.value;
let imgDom = document.querySelector('.hero-image');
imgDom.style.backgroundColor = this.value + '40';
// imgDom[0].style.backgroundColor = this.value;
});
</script>
</body>
</html>
解决方案
您可以简单地添加overflow: hidden;
到父级并删除其他border-radius
属性,display: flex
这会导致 safari 中的显示问题。
我建议按照以下内容进行一些更新,以帮助图像缩放:
img {
width: 100%;
height: auto;
}
.hero-image {
position: relative;
max-width: 200px;
max-height: 200px;
background-color: #ff000050;
border-radius: 90px;
overflow: hidden;
}
.hero-image:after {
position: absolute;
height: 100%;
width: 100%;
background-color: inherit;
top: 0;
left: 0;
display: block;
content: "";
}
容器父级的半径 + 溢出应该是所有需要的,额外的子属性是多余的。
推荐阅读
- c# - 使用 SQL Server 中的 where 子句在所有行中更新相同的结果
- java - Aframe 中的第二个 uv 用于环境光遮蔽
- python - 如何将json类型数据转换为pandas数据框
- mysql - 当 usedIf 在数据库中时,sequelize findOne 找不到 userId
- c# - 在winforms c#中从网站中提取数据
- javascript - 发送 (JavaScript / Ajax) 和接收 (PHP) 文件没有 utf8 问题
- java - 如何将音频文件保存在 Android Studio 的存储中?
- c# - 从 JSON 文件中对元素进行排序并将它们保存在字典中
- javascript - 在 Java Script 中获取 .then 中的 response.status
- c# - Hello World dotnet 核心示例不起作用