Javascript 根据h2中的文本更改背景图像
我有一个h2标题,有一个背景图像的几个页面。如何根据h2中的文本更改背景url 如果text=传单使用url1 如果text=明信片使用url2等Javascript 根据h2中的文本更改背景图像,javascript,jquery,Javascript,Jquery,我有一个h2标题,有一个背景图像的几个页面。如何根据h2中的文本更改背景url 如果text=传单使用url1 如果text=明信片使用url2等 我想构建一个函数,然后只运行这两个参数的函数。对于这个特定场景,您必须使用Javascript function changeBackground() { const h2 = $("h2"); // change with your h2 selector const text =
我想构建一个函数,然后只运行这两个参数的函数。对于这个特定场景,您必须使用Javascript
function changeBackground() {
const h2 = $("h2"); // change with your h2 selector
const text = h2.text();
if (text === "flyers") {
h2.css("background-image", url1)
}
else if (text === "postcards") {
h2.css("background-image", url2);
}
}
changeBackground();
这可能对你有帮助-
const h2 = document.querySelector('h2'); // Your H2 element
const elemWithBg = document.querySelector('div'); // elem that shows backgroud
if (h2. textContent === 'flyers') {
elemWithBg.style.backgroundImage = `url(/path/to/first/image.jpg)`;
} else if (h2. textContent === 'postcards') {
elemWithBg.style.backgroundImage = `url(/path/to/second/image.jpg)`;
}
对于这个特定场景,您必须使用Javascript 这可能对你有帮助-
const h2 = document.querySelector('h2'); // Your H2 element
const elemWithBg = document.querySelector('div'); // elem that shows backgroud
if (h2. textContent === 'flyers') {
elemWithBg.style.backgroundImage = `url(/path/to/first/image.jpg)`;
} else if (h2. textContent === 'postcards') {
elemWithBg.style.backgroundImage = `url(/path/to/second/image.jpg)`;
}
谢谢你的帮助。这是我的网站。我的h2是我的BG图像。这就是我现在拥有的$('.litHeader').text(函数(i,currentText){if(currentText==“Flyers”){$('.litHeader').style.backgroundImage=
url(https://cms-assets.tutsplus.com/uploads/users/2092/posts/35085/image/business_flyer_1b.jpg)
;}}谢谢你的帮助。这是我的网站。我的h2是我的BG图像。这是我现在拥有的。$('.litHeader')。text(函数(i,currentText){if(currentText==“传单”){$('.litHeader').style.backgroundImage=url(https://cms-assets.tutsplus.com/uploads/users/2092/posts/35085/image/business_flyer_1b.jpg)
;}