Changing background image using Javascript

落爺英雄遲暮 提交于 2019-12-06 15:48:27

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.

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;

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