2016-06-25 82 views
1

下面的行不代碼工作不改變,背景圖像中的JavaScript

document.getElementById("image").style.backgroundImage =url(previewPic.src); //not working 

HTML:

<div id = "image"> 
    Hover over an image below to display here. 
</div> 

<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()"> 

<img class = "preview" alt = "With My Boy" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG" onmouseover = "upDate(this)" onmouseout = "unDo()"> 

<img class = "preview" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg" alt = "Young Puppy" onmouseover = "upDate(this)" onmouseout = "unDo()"> 

CSS:

/*Name this external file gallery.css*/ 
body{ 
     margin: 2%; 
     border: 1px solid black; 
     background-color: #b3b3b3; 
} 
#image{ 
    line-height:650px; 
     width: 575px; 
    height: 650px; 
     border:5px solid black; 
     margin:0 auto; 
    background-color: #8e68ff; 
    background-image: url(''); 
    background-repeat: no-repeat; 
    color:#FFFFFF; 
    text-align: center; 
    background-size: 100%; 
    margin-bottom:25px; 
    font-size: 150%; 
} 
.preview{ 
     width:10%; 
     margin-left:17%; 
    border: 10px solid black; 
} 
img{ 
     width:95%; 
} 

JS:

/*Name this external file gallery.js*/ 

function upDate(previewPic){ 
console.log(previewPic.src); 
console.log(previewPic.alt); 
document.getElementById("image").style.backgroundColor = "#CCEECC";//worked 
document.getElementById("image").innerHTML=previewPic.alt;//worked 
document.getElementById("image").style.backgroundImage =url(previewPic.src); //not working 

    } 

    function unDo(){ 
    /* In this function you should 
    1) Update the url for the background image of the div with the id = "image" 
    back to the orginal-image. You can use the css code to see what that original URL was 

    2) Change the text of the div with the id = "image" 
    back to the original text. You can use the html code to see what that original text was 
    */ 

    } 

CodePen

回答

2

previewPic.src級聯內的字符串象下面這樣:

document.getElementById("bg").style.backgroundImage = 'url('+previewPic.src+')'; 

previewPic = { 
 
    src: 'https://unsplash.it/200/200?image=55' 
 
} 
 
document.getElementById("bg").style.backgroundImage = 'url('+previewPic.src+')';
div { 
 
    width:200px; 
 
    height:200px; 
 
    background-size:cover 
 
}
<div id="bg"></div>