Thuộc tính style.opacity trong HTML DOM trả về và cho phép thay đổi giá trị của thuộc tính CSS opacity của một phần tử trong tài liệu HTML. Giá trị từ 0 (hoàn toàn trong suốt) đến 1 (hoàn toàn không trong suốt).
Cú pháp
Lấy giá trị opacity
object.style.opacity
Thay đổi opacity
object.style.opacity = "value"
Ví dụ
Ví dụ sử dụng thuộc tính style.opacity:
<!DOCTYPE html>
<html>
<head>
<style>
body { color: #000; background: lightblue; height: 100vh; }
p { background: #1f13db; height: 50px; width: 100%; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; }
</style>
</head>
<body>
<h1>Ví dụ thuộc tính style opacity DOM</h1>
<p></p>
<button onclick="add()" class="btn">Thêm opacity</button>
<script>
function add() {
document.querySelector('p').style.opacity = "0.2";
}
</script>
</body>
</html>
Kết quả
Nhấn nút Thêm opacity để thêm thuộc tính opacity cho phần tử.