[英]Why can't I set z-index through javascript with this function? (I know about camelcase)
Hi I want to change the z-index
of my DOM element, so I used a function to do so. 嗨,我想更改我的DOM元素的
z-index
,所以我使用了一个函数来实现。 The function works for many properties but not z-index
I am using Dev Tools and I can see that it is not even being set on the element and I do not know why. 该函数适用于许多属性,但不适用于
z-index
我正在使用Dev Tools,我可以看到它甚至没有在元素上设置,我不知道为什么。
Javascript: 使用Javascript:
function setStyle(obj, propertyObj) {
for (var property in obj) {
if(obj.hasOwnProperty(property)){
obj.style[property] = propertyObj[property];
}
}
}
var img = new Image();
img.onload = function() {
setStyle(this, {'zIndex':'-5'}) ;
};
img.src = 'test.jpg'
EDIT 编辑
Thanks for the good answers. 谢谢你的好答案。
I was applying a border
in the CSS code somewhere, so when I was looping through the objects properties border
was being changed (but the same was not true for z-index
). 我在某个地方的CSS代码中应用了一个
border
,所以当我循环遍历对象时,属性border
正在被更改(但z-index
并非如此)。
function setStyle(el, propertyObj) {
for (var property in propertyObj){
el.style[property] = propertyObj[property]
}
}
var img = new Image();
img.onload=function(){
setStyle(this,{
'zIndex':"999"
});
};
if(obj.style && obj.style.hasOwnProperty(property)){
obj.style[property] = propertyObj[property];
}
使用JS设置z-index就像这样简单:
document.getElementById('IDHERE').style.zIndex = "2000";
You have 2 errors: 你有2个错误:
Your for in loop
is looping through image object, not the properties object. for in loop
是循环遍历图像对象,而不是属性对象。
Your hasOwnProperty
check is wrong (and unnecessary). 你的
hasOwnProperty
检查是错误的(并且是不必要的)。 You're checking to see if the obj has your style props, not whether the style object has the style props 您正在检查obj是否具有您的样式道具,而不是样式对象是否具有样式道具
It should read: 它应该是:
function setStyle(obj, propertyObj) {
for (var property in propertyObj) {
obj.style[property] = propertyObj[property];
}
}
Might as well add yet another answer... 不妨再添一个答案......
typeof obj.style === 'object' && Object.keys(propertyObj).forEach(function(key) {
obj.style[key] = propertyObj[key];
});
IMO, Object.keys
is superior to a for ... in
loop as it is immune from Object
prototype injection problems. IMO,
Object.keys
优于for ... in
循环,因为它不受Object
原型注入问题的影响。
This also ensures that obj
has a style
property to begin with. 这也确保了
obj
具有一个style
属性。
Because some people are in to micro-optimisation, here it is without the Array.forEach
因为有些人正在进行微优化,所以没有
Array.forEach
if (typeof obj.style === 'object') {
var keys = Object.keys(propertyObj);
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
obj.style[key] = propertyObj[key];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.