简体   繁体   English

使用Javascript访问DOM中的Element属性值

[英]Accessing Element property value in DOM using Javascript

I am trying to access the property of an element in my page. 我正在尝试访问页面中元素的属性。 My ultimate goal is to switch a float property from left to right or vice versa if an onClick event happens. 我的最终目标是,如果发生onClick事件,则将float属性从左切换为右,反之亦然。 However, I am not having any luck even accessing an element. 但是,我什至没有访问任何元素的运气。

I am trying to access the width property just to test and make sure my logic and code works. 我试图访问width属性只是为了测试并确保我的逻辑和代码正常工作。 With the follwing code I get a 'null' return for myElement2 and I have also tried the myElement.style.getCSSPropertyVlaue function which my debugger says doesn't exist. 使用下面的代码,我得到myElement2的“ null”返回值,并且还尝试了myElement.style.getCSSPropertyVlaue函数,调试器说该函数不存在。

I am using Firefox debugger to test if this makes a difference. 我正在使用Firefox调试器测试这是否有所作为。

var myElement = document.getElementById('leftPic');
var myElement2 = myElement.style.getPropertyValue('width');

console.log(myElement);
console.log(myElement2);
console.log('Test');

You are using the incorrect code to get a CSS property's value with JavaScript. 您使用了不正确的代码来通过JavaScript获取CSS属性的值。 You want to use... 您要使用...

var myElement = document.getElementById('leftPic'),
var myElement2 = window.getComputedStyle(myElement).getPropertyValue('width');

Also, I'd choose a better variable name for storing the width in, as myElement2 is misleading. 另外,我会选择一个更好的变量名称来存储宽度,因为myElement2具有误导性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM