Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy giá trị hiện tại của thuộc tính CSS trong JavaScript


Phương thức getComputedStyle() trả về đối tượng chứa tất cả style áp dụng cho phần tử.

Ví dụ

Các ví dụ minh họa lấy giá trị thuộc tính 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>

Kết quả

Kết quả như hình (hiển thị background-color đã tính).

Ví dụ 2

<!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>

Kết quả

Kết quả như hình (hiển thị box-shadow đã tính).