Javascript массив кнопок назад и вперед - PullRequest
0 голосов
/ 09 февраля 2019

У меня сейчас проблема с проектом, над которым я сейчас работаю, где мне нужно создать машину котировок с 5 цитатами.Мне нужно иметь кнопку вперед и назад для цитаты.В настоящее время у меня все в основном сделано, но когда я нажимаю кнопку вперед и достигаю последней цитаты, если я продолжаю нажимать, я получаю неопределенное значение в своем элементе, который я просто хочу, чтобы он остановился на последнем или вернулся к первомуи то же самое происходит, когда я нажимаю кнопку возврата.Пожалуйста, помогите.

Вот мой код.

var quoteArray = ["If you're already a front-end developer, well, pretend you're also wearing a pirate hat. - Ethan Marcotte, Responsive Web Design",
"Website without visitors is like a ship lost in the horizon. - Dr. Christopher Dayagdag",
"If there's one thing you learn by working on a lot of different Web sites, it's that almost any design idea--no matter how appallingly bad--can be made usable in the right circumstances, with enough effort.” - Steve Krug, Don't Make Me Think: A Common Sense Approach to Web Usability",
"The true ENTREPRENEUR is a risk taker, not an excuse maker. - VDEXTERS",
"Being first in the search result organically in Google is the dream of all website owners. ― Dr. Chris Dayagdag"];

var i = 0;
var backButton = document.getElementById("back");
var forwardButton = document.getElementById("forward");




    document.querySelector(".quote")
        .innerHTML = quoteArray[0];


setInterval(function() {
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i++];

        if (i == quoteArray.length) i = 0;
},5000);


backButton.addEventListener("click", function() {
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i--];

        if(quoteArray.length == -1) {
            document
            .querySelector(".quote")
            .innerHTML = quoteArray[4];
        }
    
})

forwardButton.addEventListener("click", function() {
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i++];

        if(quoteArray.length == 5) {
            document
            .querySelector(".quote")
            .innerHTML = quoteArray[0];
        }
    
})
body {
    width: 100%;
    height: 100%;
}

a, .hero{
    color: rgb(255, 255, 255);
}


#back, #forward {
    font-size: 30px;
}

.nav {
    display: flex;
    justify-content: space-between;
    align-items:center;
    color: rgb(255, 255, 255);
    width: 100%;
}

.hero {
    background-image: linear-gradient(
      rgb(0, 0, 0, 0.3) 10%,
      rgba(0, 0, 0, 0.5) 50%,
      rgba(0, 0, 0, 0.5) 50%,
      rgba(0, 0, 0, 0.3) 80%
    ),
    url(./images/landscape-3969127_1280.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    height: 400px;
}
.row {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 70%;
}

#back, #forward {
    padding-left: 10px;
    padding-right: 10px;
}

.buttons {
    padding: 20px;
}

.quote {
    font-size: 18px;
    font-weight: bold;
}

.logo {
    margin: 0 50px;
}

ul {
    display: flex;
    justify-content: center;
    margin-right: 50px;
    padding: 0px;
}

ul a {
    padding-left: 30px;
    padding-right: 30px;
    text-decoration: none;
    font-size: 20px;
    font-weight: bold;
}

li {
    list-style: none;
}
.nav a {
    color: rgb(255, 255, 255)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    

    <div class="hero">
            <div class="nav">
                    <div class="logo"><h1>Logo</h1></div>
                    <ul>
                        <a href="#">
                            <li>Link</li>
                        </a>
                        <a href="#">
                            <li>Link</li>
                        </a>
                        <a href="#">
                            <li>Link</li>
                        </a>
                    </ul>
                </div>
        <div class="row">
                <div class="quote"></div>
        </div>
        <div class="buttons">
                <a href="#"><i id="back" class="far fa-arrow-alt-circle-left"></i></i></a>
                <a href="#"><i id="forward" class="far fa-arrow-alt-circle-right"></i></i></a>
        </div>
    </div>

    

    <script src="./quote.js"></script>
</body>
</html>

1 Ответ

0 голосов
/ 09 февраля 2019

% твой друг.Вы получаете неопределенный, потому что вы пытаетесь получить доступ к элементу за пределами списка.Позвольте мне подняться так высоко, как вы хотите, и так низко, как вы хотите, и просто выполнить эти вычисления

увеличение:

quoteArray[i++ % quoteArray.length]

уменьшение:

i = (i - 1 + quoteArray.length) % quoteArray.length;
quoteArray[i]

var quoteArray = ["If you're already a front-end developer, well, pretend you're also wearing a pirate hat. - Ethan Marcotte, Responsive Web Design",
"Website without visitors is like a ship lost in the horizon. - Dr. Christopher Dayagdag",
"If there's one thing you learn by working on a lot of different Web sites, it's that almost any design idea--no matter how appallingly bad--can be made usable in the right circumstances, with enough effort.” - Steve Krug, Don't Make Me Think: A Common Sense Approach to Web Usability",
"The true ENTREPRENEUR is a risk taker, not an excuse maker. - VDEXTERS",
"Being first in the search result organically in Google is the dream of all website owners. ― Dr. Chris Dayagdag"];

var i = 0;
var backButton = document.getElementById("back");
var forwardButton = document.getElementById("forward");




    document.querySelector(".quote")
        .innerHTML = quoteArray[0];


setInterval(function() {
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i++ % quoteArray.length];
}, 5000);


backButton.addEventListener("click", function() {
    i = (i - 1 + quoteArray.length) % quoteArray.length;
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i];
    
})

forwardButton.addEventListener("click", function() {
    document
        .querySelector(".quote")
        .innerHTML = quoteArray[i++ % quoteArray.length];
    
})
body {
    width: 100%;
    height: 100%;
}

a, .hero{
    color: rgb(255, 255, 255);
}


#back, #forward {
    font-size: 30px;
}

.nav {
    display: flex;
    justify-content: space-between;
    align-items:center;
    color: rgb(255, 255, 255);
    width: 100%;
}

.hero {
    background-image: linear-gradient(
      rgb(0, 0, 0, 0.3) 10%,
      rgba(0, 0, 0, 0.5) 50%,
      rgba(0, 0, 0, 0.5) 50%,
      rgba(0, 0, 0, 0.3) 80%
    ),
    url(./images/landscape-3969127_1280.jpg);
    background-size: cover;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-direction: column;
    height: 400px;
}
.row {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    width: 70%;
}

#back, #forward {
    padding-left: 10px;
    padding-right: 10px;
}

.buttons {
    padding: 20px;
}

.quote {
    font-size: 18px;
    font-weight: bold;
}

.logo {
    margin: 0 50px;
}

ul {
    display: flex;
    justify-content: center;
    margin-right: 50px;
    padding: 0px;
}

ul a {
    padding-left: 30px;
    padding-right: 30px;
    text-decoration: none;
    font-size: 20px;
    font-weight: bold;
}

li {
    list-style: none;
}
.nav a {
    color: rgb(255, 255, 255)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    

    <div class="hero">
            <div class="nav">
                    <div class="logo"><h1>Logo</h1></div>
                    <ul>
                        <a href="#">
                            <li>Link</li>
                        </a>
                        <a href="#">
                            <li>Link</li>
                        </a>
                        <a href="#">
                            <li>Link</li>
                        </a>
                    </ul>
                </div>
        <div class="row">
                <div class="quote"></div>
        </div>
        <div class="buttons">
                <a><i id="back" class="far fa-arrow-alt-circle-left"></i></a>
                <a><i id="forward" class="far fa-arrow-alt-circle-right"></i></a>
        </div>
    </div>

    

    <script src="./quote.js"></script>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...