如何使用JavaScript创建内容滑块?

时间:2014-03-16 08:23:50

标签: javascript html css

我正在尝试使用JavaScript制作内容滑块。在查看Google的示例后,就我所知:

HTML:

<div class = "nav">
    <div class = "navItem" data-pos = "0px" >item1</div>
    <div class = "navItem" data-pos = "-1200px">item2</div>
    <div class = "navItem" data-pos = "-2400px">item3</div>
    <div class = "navItem" data-pos = "-3600px">item4</div>
</div>
<div class = "container">
    <div class = "wrapper">
        <div class = "item1 content"></div>
        <div class = "item2 content"></div>
        <div class = "item3 content"></div>
        <div class = "item4 content"></div>
    </div>
</div>  

CSS:

.nav {
    position: relative;
    top: 170px;
    width: 1200px;
    height: 200px;
    margin: 10px auto;
    font-family: 'NavFont';
    font-size: 20px;
}
.navItem {
    width: 280px;
    background: #CCB095;
    padding: 100px 0;
    border-radius: 100%;
    float: left;
    margin: 10px;
}
.navItem:hover {
    background: white;
}   
.navItem .active {
    background: red;
}
.container {
    width: 1200px;
    height: 700px;
    overflow: hidden;
    position: relative;
    top: 200px;
    margin: 0px auto;
}
.wrapper {
    width: 4800px;
    height: auto;
    position: absolute;
}
.content {
    width: 1200px;
    height: 700px;
    float: left;
}
.item1 {
    background: red;
}
.item2 {
    background: green;
}
.item3 {
    background: blue;
}
.item4 {
    background: yellow;
}

JavaScript的:

var links = document.querySelectorAll(".navItem");
var wrapper = document.querySelector(".wrapper");

for (var i = 0; i < links.length; i++) {
    var link = links[i];
    link.addEventListener('click', setPosition, false);
}

addClass(links[0], "active");

function addClass(element, classToAdd){
    var CurrentClassValue = element.className;

    if(CurrentClassValue.indexOf(classToAdd) == -1){
        if ((CurrentClassValue == null) || (CurrentClassValue === "")) {
            element.className = classToAdd;
        }
        else {
            element.className += " " + classToAdd;
        }
    }
}

function removeLinks() {
    for (var i = 0; i < links.length; i++) {
        removeClass(links[i], "active");
    }
}

function removeClass(element, classToRemove) {
    var CurrentClassValue = element.className;

    if (CurrentClassValue.indexOf(classToRemove) != -1) {
        element.className = element.className.replace(classToRemove, "");
        return;
    }

    if(CurrentClassValue.indexOf(classToRemove + " ") != -1){
        element.className = element.className.replace(classToRemove + " ", "");
        return;
    }

    if(CurrentClassValue.indexOf(" " + classToRemove) != -1){
        element.className = element.className.replace(" " + classToRemove, "");
        return;
   }
}

function setPosition (e) {
    removeLinks();

    var clickedLink = e.target;
    addClass(clickedLink, "active");
    var position = clickedLink.getAttribute("data-pos");
    wrapper.style.left = position;
}

0 个答案:

没有答案