我可以console.log(2),但是当我想显示'div'的不透明性时它不起作用?
let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click', function() {
console.log(obj.style.opacity);
console.log(2);
})
<div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
<button id="fade-btn">click</button>
答案 0 :(得分:1)
尝试
console.log( window.getComputedStyle(obj).getPropertyValue('opacity');
答案 1 :(得分:0)
您必须设置opacity
才能看到
let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click',function(){
console.log(obj.style.opacity);
});
#fade-obj{
width:300px;
height:300px;
background:#000;
}
<div id="fade-obj" style="opacity:1"></div>
<button id="fade-btn">click</button>
或使用window.getComputedStyle(obj).getPropertyValue('opacity')
let obj = document.getElementById('fade-obj');
let btn = document.getElementById('fade-btn');
btn.addEventListener('click',function(){
console.log(window.getComputedStyle(obj).getPropertyValue('opacity'));
});
#fade-obj{
width:300px;
height:300px;
background:#000;
}
<div id="fade-obj"></div>
<button id="fade-btn">click</button>
答案 2 :(得分:0)
添加一些默认的不透明度值以检查value。说opacity:2
console.log(document.getElementById('fade-obj').style.opacity);
<div id="fade-obj" style="width:30px;height:30px;background:#000;opacity:2"></div>
答案 3 :(得分:0)
问题在于,当您不设置不透明度时,浏览器会为您设置它。因此,不透明度不是来自CSS本身。相反,它是经过计算的。使用以下方法获取价值:
let obj = document.getElementById('fade-obj');
window.getComputedStyle(obj).getPropertyValue('opacity');