分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

原生js获取元素样式值

发布时间:2023-09-06 01:06责任编辑:林大明关键词:js

在学习js初期,就一直有一个疑问,获取元素样式的值,不是直接使用
obj.style.left之类的就可以得到了吗?可是使用这样的方式,有的时候能够获取得到,有的时候又不能获取,一直疑惑不已,但是由于以前学习态度的问题,也没有深究,今天专门花了点时间整理了一下这方面的知识。

样式

首先,我们要明确样式的种类有以下三种

  • 内联样式: 也就是行内样式,直接写在DOM元素的style属性中
  • 嵌入样式: 写在html页面中的<style></style>中的样式
  • 外部样式: 由link标签引入的css文件中的样式
    优先级:内联 > 嵌入 > 外部

首先,先写一个例子来测试一下通过style方法获取元素样式的值,思路是,一个样式写在行内,一个样式写在style标签中,一个样式由link引入

<head> ???<meta charset="UTF-8"> ???<title>get style</title> ???<style> ???????<!-- 嵌入样式 --> ???????.box { ???????????height: 200px; ???????} ???</style> ???<!-- 引入外部样式 --> ???<link rel="stylesheet" href="./index.css"></head><body> ???<!-- 行内样式 --> ???<div class="box" style="width: 100px;"></div></body>
// index.css.box { background-color: orange; }
// javascriptvar box = document.getElementsByClassName(‘box‘)[0];console.log(box.style.width);console.log(box.style.height);console.log(box.style.backgroundColor);

得到的结果为:

‘100px‘‘‘‘‘

因此我们可以看到height值和backgroundColor值没有被获取到,所以我们得到以下结论:
style只能获取行内样式的值,无法获取嵌入式样式和外部样式的值

那么嵌入式样式和外部样式的值应该怎么办呢,看下面代码

// currentStyle: IE下获取元素样式的值if ( box.currentStyle ) { ???console.log( ‘this is IE.‘ ); ???console.log( box.currentStyle.width ); ???console.log( box.currentStyle.height ); ???console.log( box.currentStyle.backgroundColor );} else { ???// chorme and firefox ???console.log( document.defaultView.getComputedStyle(box, false).width ); ???console.log( document.defaultView.getComputedStyle(box, fasle).height ); ???console.log( document.defaultView.getComputedStyle(box, false).backgroundColor );}

输出结果

‘this is IE.‘‘100px‘‘200px‘‘orange‘

分别在IE, chrome, firefox下测试一下,最后都能够获取所有的属性。非常好,于是我们可以得出结论
获取元素样式值的最佳方式,就是通过obj.currentStyle 或者
document.defaultView.getComputedStyle( obj, false ) 的方式,其中前者适用于IE,后者适用于chrome和Firefox

因此我们可以写一个获取元素样式值的方法

var getStyle = function(obj, key) { ???return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle( obj, false )[key];}




原生js获取元素样式值

原文地址:http://www.cnblogs.com/chenmingchao/p/7427304.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved