Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm thế nào để Nhận Giá trị Hiện tại của Thuộc tính CSS trong JavaScript?

Phương thức getComputedStyle () cung cấp một đối tượng bao gồm tất cả các kiểu được áp dụng cho phần tử đích.

Ví dụ

Các ví dụ sau minh họa cách chúng ta có thể lấy và đặt các biến CSS bằng JavaScript.

<!DOCTYPE html>
<html>
<head>
<style>
div {
   margin: 4%;
   padding: 4%;
   width: 50%;
   text-align: center;
   background-color: powderblue;
   border-radius: 4%;
}
</style>
</head>
<body>
<div>Test Div</div>
<span></span>
<script>
let element = document.querySelector('div');
let getStyle = window.getComputedStyle(element);
document.querySelector('span').textContent = ('background-color: ' + getStyle.getPropertyValue('background-color') + '.');
</script>
</body>
</html>

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Làm thế nào để Nhận Giá trị Hiện tại của Thuộc tính CSS trong JavaScript?

Ví dụ

<!DOCTYPE html>
<html>
<head>
<style>
div {
   display: flex;
   margin: 4%;
   padding: 4%;
   width: 20vh;
   height: 20vh;
   box-shadow: inset 0 0 23px cadetblue;
   border: 2px groove green;
   border-radius: 50%;
}
</style>
</head>
<body>
<div><div></div></div>
<span></span>
<script>
let element = document.querySelector('div');
let getStyle = window.getComputedStyle(element);
document.querySelector('span').textContent = ('box-shadow: ' + getStyle.getPropertyValue('box-shadow') + '.');
</script>
</body>
</html>

Đầu ra

Điều này sẽ tạo ra kết quả sau -

Làm thế nào để Nhận Giá trị Hiện tại của Thuộc tính CSS trong JavaScript?