Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ดึงค่าปัจจุบันของ CSS Property ด้วย JavaScript (getComputedStyle)

ตัวอย่างที่ 1

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

ผลลัพธ์: แสดงค่า background-color ที่คำนวณแล้ว

ตัวอย่างที่ 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>

ผลลัพธ์: แสดงค่า box-shadow ที่คำนวณแล้ว