你能链接 backgroundImage 和 backgroundPosition 吗?

Can you chain backgroundImage and backgroundPosition?

无法弄清楚如何通过 DOm 方法使用 backgroundImage 和 backgroundPosition。想使用背景图片和调整定位

 window.onload = function() {
var slime =  "url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1)";
   document.getElementsByTagName('main').style.backgroundImage = "url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1)";
slime.style.backgroundPosition = '25% 75%';
};

为了清楚起见,我将其分解并添加评论(然而,@A Haworth 上面所说的是正确的)。

window.onload = function() {
  // define and store image url with proper formatting
  var slime =  "url('https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1')";

  // get the main element from the DOM (there are multiple ways of accomplishing this)
  let main = document.querySelector('main');

  // set background image of main element
  main.style.backgroundImage = slime;

  // set position of background image
  main.style.backgroundPosition = '25% 75%';
)};

“链接” CSS 属性称为 shorthand,它可以应用于某些 CSS 属性。幸运的是 backgound 属性 做到了,这是列表:

背景:

  • background-color
  • background-image
  • background-repeat
  • background-attachment
  • background-position

它必须按照 space 分隔的顺序,并且可以省略任何值(但至少需要一个)。所以 OP 将是:

background: url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1) 25% 75%

/* You should add "no-repeat" betwwen -image and -position if the image dimensions 
are smaller than the element's dimension, unless you want a wallpaper effect */

property: value 与它一起被称为 CSS ruleset. In order to actually apply any CSS ruleset to an element inline with the .style property, is to use .setProperty() 方法。

node.style.setProperty(property, value);

const main = document.querySelector('main');

const property = 'background';

const value = `url(https://www.dropbox.com/s/scdx0a0ck16abtv/slime.jpg?raw=1) 25% 75%`;

main.style.setProperty(property, value);
html,
body {
  width: 100%;
  height: 100%
}

main {
  min-height: 100%;
}
<main></main>