HTML opacity attribute vs CSS opacity

♀尐吖头ヾ 提交于 2021-02-20 19:31:11

问题


I know of two different ways of setting opacity in HTML:

<div opacity="0.5"></div> and

<div style="opacity: 0.5;"></div>

I also know how to set both of those in JavaScript:

div.setAttribute("opacity", 0.5); and

div.style.opacity = 0.5

Are there any major differences between those two methods? Should I prefer one over the other? (I guess I should at least be consistent)


回答1:


The only opacity attribute I am aware of is for use with SVGs:

Example Elements

The following elements can use the opacity attribute

Graphics elements [and] <a> <defs> <glyph> <g> <marker> <missing-glyph> <pattern> <svg> <switch> <symbol>

Your <div opacity="0.5"></div> doesn't work in HTML and therefore, to style HTML elements, opacity should be controlled with CSS.




回答2:


CSS is always faster than Javascript. If your are able to do anything with CSS then why waste time with Javascript.

CSS precedence rules say inline and html attribute are given higher order then External or Embedded CSS. However inline CSS is not good practice, until it is required in your project for certain reason

Proper CSS opacity code:

img {
    opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
}

https://css-tricks.com/almanac/properties/o/opacity/

img {
  /* Theoretically for IE 8 & 9 (more valid) */
  /* ...but not required as filter works too */
  /* should come BEFORE filter */
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; // IE8

  /* This works in IE 8 & 9 too */
  /* ... but also 5, 6, 7 */
  filter: alpha(opacity=50); // IE 5-7

  /* Modern Browsers */
  opacity: 0.5;
}


来源:https://stackoverflow.com/questions/31511962/html-opacity-attribute-vs-css-opacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!