你能链接backgroundImage和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属性被称为简写,它可以应用于一些CSS属性。幸运的是,backgound属性确实如此,下面是列表:

背景:

  • 背景色
  • 背景图像
  • 背景重复
  • 背景附件
  • 背景位置

它必须以空格分隔,并且任何值都可以省略(但至少需要一个(。所以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规则集。为了将任何CSS规则集实际应用于与.style属性内联的元素,需要同时使用.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>

相关内容

  • 没有找到相关文章

最新更新