简体   繁体   中英

HTML/JS: Setting “100% auto” for background-size property truncates to “100%” but “auto 100%” does not

For a div, why does setting "100% auto" for the background-size property get truncated to "100%" but "auto 100%" does not?

The goal is to allow "100% auto" for the background-size property.

"100% auto" is different from "100%", isn't it?

Codepen: https://codepen.io/anon/pen/xMLXKz?editors=1111

<div id="test1"></div>
<div id="test2"></div>

div {
  width: 200px;
  height: 200px;
  background: blue;
}

$("#test1")[0].style["background-size"] = "100% auto";
$("#test2")[0].style["background-size"] = "auto 100%";

console.log($("#test1")[0].style["background-size"]);
console.log($("#test2")[0].style["background-size"]);

console.log("Done")

This outputs:

"100%"
"auto 100%"
"Done"

As you can check here at MDN - background-size , it clearly says when the second value ( ie height ) is absent, the browser will treat as auto .

So, I think it's okay to check for a /\\s/ character in your $("#test1")[0].style["background-size"] value to check for a space, and if it wasn't there ( RegExp returned -1 ) append an auto to the output to become 100% auto .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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