如何使项目中的背景图像过渡平滑?

时间:2019-05-03 11:49:10

标签: javascript html css

我正在构建我的第一个javascript项目并制作一个随机报价生成器。我想在我的项目中实现平稳的背景转换,但是我无法实现。

我已经尝试过处理过渡属性和动画属性,但似乎没有任何效果。

HTML代码:

<body>
    <div id="quote-box" class="quotes">
        <div id="text"></div>
        <div id="author"></div>
        <div class="links">
            <a id="twitter-quote" href="https://twitter.com/intent/tweet?text=" target="_blank"><i class="fab fa-twitter"></i></a>
            <a id="tumblr-quote" href="https://twitter.com/intent/tweet?text=${quote}" target="_blank"><i class="fab fa-tumblr"></i></a>
            <a id="new-quote" href="#">New Quote</a>
        </div>
    </div>

    <script src="./main.js"></script>

</body>

CSS代码:

body{
    width: 100vw;
    height: 100vh;
}

.quotes{
    position: absolute;
    width: 37.5rem;
    bottom: 60px;
    left: -37.5rem;
    min-height: 100px;
    padding: 1.4rem;
    background-color: #eee;
    border-top-right-radius: .3rem;
    border-bottom-right-radius: .3rem;
    overflow: hidden;
    text-align: justify;
    background-color: rgba(255, 255, 255, 0.6);
    opacity: 0;
}

.slide{
    transform: translateX(37.5rem);
    opacity: 1;
    transition: all 0.7s ease-in-out 0.3s;
}

JavaScript代码:

function setupQuotes() {
    fetch('https://raw.githubusercontent.com/smartdev007/Avengers-Quote/master/quotes.json')
    .then(response => response.json())
    .then(data => {

        function getRandomQuote() {
            if (quoteBox.classList.contains('slide')) {
                quoteBox.classList.remove('slide')
            }

            const randomIdx = parseInt(Math.random() * data.length);
            const { quote, author, url } = data[randomIdx];

            tweetBtn.setAttribute('href', `https://twitter.com/intent/tweet?text=${quote}`);
            tumblrBtn.setAttribute('href', `https://twitter.com/intent/tweet?text=${quote}`);

            setTimeout(() => {
                document.getElementById('text').innerHTML = `<span class="big-quote">&#8220;</span>
                ${quote}`;
                document.getElementById('author').innerHTML = `-${author}`;
                document.body.style.background = `url('${url}') no-repeat center top/cover`;
                quoteBox.classList.add('slide');
            }, 500)
          }

          newQuote.addEventListener('click', getRandomQuote);

          getRandomQuote();
        })
    .catch(e => console.log(e));
}

完整项目的Codepen链接: https://codepen.io/FuriousJK/pen/YMoNgZ

我正在尝试实现这种过渡:https://codepen.io/bradtraversy/full/oVPBaa

1 个答案:

答案 0 :(得分:1)

将此添加到正文:

 transition: background 1s ease-in-out;
-moz-transition: background 1s ease-in-out;
-webkit-transition: background 1s ease-in-out;

https://codepen.io/anon/pen/bybGew