Changing background image using Javascript

房东的猫 提交于 2019-12-07 19:25:08

问题


I have been trying to create a slideshow on one of the web pages I've been creating. I have created a div with a unique class name that is targeted in order to change the background image using JavaScript. So far, I have been able to do the following:

  1. Capture the div where I want to change the background image by using the querySelector
  2. Attempted to change the background image of said div using JavaScript

I have been debugging this function using DevTools, yet I cannot figure out why the image won't change. Any idea what is happening here? I have included snippets of the code below. Thank you.

HTML

<div class="content-one-right">
  <div class="inner-content-one-right">
    <div class="slideshow-container">
      <a class="prev" onclick="transitionSlides(-1)">&#10094;</a>
      <a class="next" onclick="transitionSlides(1)">&#10095;</a>
    </div>
  </div>
</div>

CSS

.content-one-right {
  grid-column: col-start 7 / span 6;
  height: 60vh;
}

.inner-content-one-right {
    height: 90%;
    width: 90%;
}

.slideshow-container {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-image: url('../images/home-slideshow/home1.jpg');
    background-repeat: no-repeat;
    background-size: cover;
}

.prev, .next {
    cursor: pointer;
    color: #FFF;
    font-weight: bold;
    font-size: 1em;
    border-radius: 0 3px 3px 0;
}

.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8);
}

JavaScript

var slideshowIndex = 0;

function transitionSlides(n) {

  var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
  slideshowIndex += n;

  if(slideshowIndex < 0) {
    slideshowIndex = images.length-1;
  }
  else if (slideshowIndex >= images.length) {
    slideshowIndex = 0;
  }

  var getContainer = document.getElementsByClassName('slideshow-container')[0];
  var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";

  getContainer.style.backgroundImage = imageToChange;

}

回答1:


I think the problem is in how you are trying to change the background image. The first time you set it, you are setting it in the stylesheet. You are using a CSS property there.

Later, you try to change it using the .style property of the element. These aren't the same thing. From this page:

The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets.

To clarify, try this in your console on this very page: document.querySelectorAll('input[type="submit"]')[3].style

This grabs the blue button at the bottom of the page that says "Post Your Answer". It's pretty clearly got a blue background that is set in the CSS. But that CSSDeclaration object in your console has only empty values. That's because it only reflects the inline styles, not the styles you applied with CSS.

Fun, right? With that knowledge, I think you can choose one way or the other to make your slideshow happen the way you expect. It's probably easiest to not use background image at all, though. I think it's conventional to have an img tag there and use javascript to set the src attribute.




回答2:


You're running into the same issue as seen in this post. There's good information provided there too. When running your code in JSFiddle, it just throws the following exception: transitionSlides is not defined. Remove the onclick handler and use addEventListener() instead. It would be best to use ID's for your prev and next buttons but this will work:

HTML:

<div class="content-one-right">
    <div class="inner-content-one-right">
        <div class="slideshow-container">
            <a class="prev">&#10094;</a>
            <a class="next">&#10095;</a>
        </div>
    </div>
</div>

JavaScript:

var slideshowIndex = 0;

document.getElementsByClassName('prev')[0].addEventListener("click", function() {
    transitionSlides(-1);
}, false);
document.getElementsByClassName('next')[0].addEventListener("click", function() {
    transitionSlides(1);
}, false);

function transitionSlides(n) {

    var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
    slideshowIndex += n;

    if(slideshowIndex < 0) {
        slideshowIndex = images.length-1;
    }
    else if (slideshowIndex >= images.length) {
        slideshowIndex = 0;
    }

    var getContainer = document.getElementsByClassName('slideshow-container')[0];
    var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";

    getContainer.style.backgroundImage = imageToChange;

}


来源:https://stackoverflow.com/questions/49289550/changing-background-image-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!