最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to set background-image property from javascript? - Stack Overflow

programmeradmin0浏览0评论

I want to set background-image property using JavaScript.

The problem is, I got image links like:

=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn/uploads/chorus_image/image/47070706/google2.0.0.jpg

When I try to set this link to style, it can't handle some characters I think.

<div style='background-image: url(urlString);'

Is there any way to handle these characters or do I need to add background-image using some other way?

I want to set background-image property using JavaScript.

The problem is, I got image links like:

https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./uploads/chorus_image/image/47070706/google2.0.0.jpg

When I try to set this link to style, it can't handle some characters I think.

<div style='background-image: url(urlString);'

Is there any way to handle these characters or do I need to add background-image using some other way?

Share Improve this question edited Feb 27, 2018 at 14:47 31piy 23.9k6 gold badges51 silver badges68 bronze badges asked Feb 27, 2018 at 14:45 hellzonehellzone 5,24626 gold badges89 silver badges159 bronze badges 2
  • 2 What does this have to do with JS? Looks like you're using an inline style attribute in HTML. – Bergi Commented Feb 27, 2018 at 14:54
  • Your title clearly says you want to do thsi from JavaScript, but the content of your question only shows HTML and an inline style. Do you need to do this in an inline style, or through JavaScript, or via a stylesheet? – T.J. Crowder Commented Feb 27, 2018 at 15:07
Add a ment  | 

5 Answers 5

Reset to default 3

Use quotes around CSS strings in url(…):

<div style='background-image: url("https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./uploads/chorus_image/image/47070706/google2.0.0.jpg");'>

You can set it like this:

var div = document.querySelector(...); // select the div
div.style.backgroundImage = "url('" + urlString + "')";

Use:

element.style.backgroundImage = "url('your cdn path')";

This is a code sippet: https://jsfiddle/fnwjhgzw/

var imageURL = 'https://cdn.vox-cdn./thumbor/Pkmq1nm3skO0-j693JTMd7RL0Zk=/0x0:2012x1341/1200x800/filters:focal(0x0:2012x1341)/cdn.vox-cdn./uploads/chorus_image/image/47070706/google2.0.0.jpg';


var imageElement = document.getElementById('image');
imageElement.style.backgroundImage = "url('"+imageURL+"')";
#image {
  height: 300px;
  background-position: center;
}
<div id="image">
</div>

element.style.backgroundImage="url('image name')"; should be used. Here element is a variable. If you want to set the background image of the web page then use document.body instead of element in the code.

发布评论

评论列表(0)

  1. 暂无评论