無法弄清楚如何將 backgroundImage 和 backgroundPosition 與 DOm 方法一起使用。希望使用背景影像并調整定位
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%';
};
uj5u.com熱心網友回復:
為了清楚起見,我將其分解并添加評論(但是,@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%';
)};
uj5u.com熱心網友回復:
“鏈接” 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452216.html
標籤:javascript html css dom
