ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>判断浏览器是否支持一个方法</title> <style type="text/css"> pre { font-size: 16px; font-weight: 700; position: absolute; left: 10px; } </style> </head> <body> <pre id="pre"> window.getComputedStyle(element, null).left; // 获取element的left样式,谷歌火狐支持。 window.getComputedStyle(element, null)["left"]; element.currentStyle.left; // IE支持 element.currentStyle["left"]; </pre> <script type="text/javascript"> function getStyle(element, attr) { // 判断浏览器是否支持这个方法 if(window.getComputedStyle) { console.log("浏览器支持window.getComputedStyle函数"); return window.getComputedStyle(element, null)[attr]; }else { console.log("浏览器支持element.currentStyle函数"); return element.currentStyle[attr]; } } window.onload = function() { var pre = document.getElementById("pre"); var left = getStyle(pre, "left"); console.log("left="+left); } </script> </body> </html> ``` 使用`element.style.left`只能获取元素的行内式的样式属性,但是使用`window.getComputedStyle(element, null).left`、 `element.currentStyle.left`无论是行内样式,内联样式、或者是外部css文件的样式都可以获取。