Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

html - img tab visibility is coming as blank

In HTML there is this tag :
<img id="img-1" src="image.jpg" alt="random" width="300" height="168"/>
In javascript code if I do :
var x = document.getElementById("img-1");
console.log(x.style.visibility) --> this displays as ""

In my css I have specified -

img {
  visibility: visible;
}

Not sure why its picking up "" as visibility

question from:https://stackoverflow.com/questions/65918902/img-tab-visibility-is-coming-as-blank

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to use window.getComputedStyle. It returns the styles applied to the element including from external stylesheets

The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets ...

element.style returns only the inline styles applied to it . eg <img style="visibility: hidden;" .... /> would've been returned by element.style.

The style read-only property returns the inline style of an element in the form of a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.

var x = document.getElementById("img-1");
console.log(x.style.visibility, window.getComputedStyle(x, null).visibility)

/*or for IE <9 compatibilty use
const visibility = window.getComputedStyle ? getComputedStyle(x, null).visibility : x.currentStyle.visibility;*/
<img id="img-1" src="image.jpg" alt="random" width="300" height="168"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...