2013-10-01 3 views
0

enter image description here Я хочу сделать навигационную панель слайдера CSS, которую я создал.Как сделать панель навигации чистого слайдера css?

Here - живая демонстрация, которую вы можете видеть.

И я также хочу, чтобы скользить изображения по горизонтали,

любая идея, как я могу добиться этого?

Было также сообщение об ошибке, когда я отправляю свой полный код, поэтому я добавил полное кодирование css в jsfiddle, не волнуйтесь, что изображения не будут отображаться, но у него есть полное кодирование.

HTML

<div class="container"> 
    <div id="content-slider"> 
     <div id="slider"> 
      <div id="mask"> 
      <ul> 
      <li id="first" class="firstanimation"> 
        <a href="#"> 
         <img src="images/img_1.jpg" alt="Cougar"/> 
        </a> 
        <div class="tooltip"> 
         <h1>Cougar</h1> 
        </div> 
       </li> 

       <li id="second" class="secondanimation"> 
        <a href="#"> 
         <img src="images/img_2.jpg" alt="Lions"/> 
        </a> 
        <div class="tooltip"> 
         <h1>Lions</h1> 
        </div> 
       </li> 

       <li id="third" class="thirdanimation"> 
        <a href="#"> 
         <img src="images/img_3.jpg" alt="Snowalker"/> 
        </a> 
        <div class="tooltip"> 
         <h1>Snowalker</h1> 
        </div> 
       </li> 

       <li id="fourth" class="fourthanimation"> 
        <a href="#"> 
         <img src="images/img_4.jpg" alt="Howling"/> 
        </a> 
        <div class="tooltip"> 
         <h1>Howling</h1> 
        </div> 
       </li> 

       <li id="fifth" class="fifthanimation"> 
        <a href="#"> 
         <img src="images/img_5.jpg" alt="Sunbathing"/> 
        </a> 
        <div class="tooltip"> 
         <h1>Sunbathing</h1> 
        </div> 
       </li> 
       </ul> 
      </div> 
     <div class="progress-bar"></div> 
     </div> 
    </div> 
</div> 

CSS

html, body { 
    background: #eaeaea url(../img/bg.png) repeat; 
    font-size: 12px; 
    font-family: "Open Sans", serif; 
    min-width: 960px; 
    margin: 0; 
    padding: 0; 
    color: #aaa; 
} 

.content h1 { 
    font-size: 48px; 
    color: #000; 
    text-shadow: 0px 1px 1px #f4f4f4; 
    text-align: center; 
    padding:60px 0 30px; 
} 

/* LAYOUT */ 
.container { 
    margin: 0 auto; 
    overflow: hidden; 
    width: 960px; 
} 

/* CONTENT SLIDER */ 
#content-slider { 
    width: 100%; 
    height: 360px; 
    margin: 10px auto 0; 
} 
/* SLIDER */ 
#slider { 
    background: #000; 
    border: 5px solid #eaeaea; 
    box-shadow: 1px 1px 5px rgba(0,0,0,0.7); 
    height: 320px; 
    width: 680px; 
    margin: 40px auto 0; 
    overflow: visible; 
    position: relative; 
} 
#mask { 
    overflow: hidden; 
    height: 320px; 
} 
#slider ul { 
    margin: 0; 
    padding: 0; 
    position: relative; 
} 
#slider li { 
    width: 680px; 
    height: 320px; 
    position: absolute; 
    top: -325px; 
    list-style: none; 
} 

#slider li.firstanimation { 
    -moz-animation: cycle 25s linear infinite; 
    -webkit-animation: cycle 25s linear infinite;   
} 
#slider li.secondanimation { 
    -moz-animation: cycletwo 25s linear infinite; 
    -webkit-animation: cycletwo 25s linear infinite;  
} 
#slider li.thirdanimation { 
    -moz-animation: cyclethree 25s linear infinite; 
    -webkit-animation: cyclethree 25s linear infinite;  
} 
#slider li.fourthanimation { 
    -moz-animation: cyclefour 25s linear infinite; 
    -webkit-animation: cyclefour 25s linear infinite;   
} 
#slider li.fifthanimation { 
    -moz-animation: cyclefive 25s linear infinite; 
    -webkit-animation: cyclefive 25s linear infinite;   
} 

#slider .tooltip { 
    background: rgba(0, 0, 0, 0.7); 
    width: 300px; 
    height: 60px; 
    position: relative; 
    bottom: 75px; 
    left: -320px; 
    -moz-transition: all 0.3s ease-in-out; 
    -webkit-transition: all 0.3s ease-in-out; 
} 
#slider .tooltip h1 { 
    color: #fff; 
    font-size: 24px; 
    font-weight: 300; 
    line-height: 60px; 
    padding: 0 0 0 20px; 
} 
#slider li#first:hover .tooltip, 
#slider li#second:hover .tooltip, 
#slider li#third:hover .tooltip, 
#slider li#fourth:hover .tooltip, 
#slider li#fifth:hover .tooltip { 
    left: 0px; 
} 
#slider:hover li, 
#slider:hover .progress-bar { 
    -moz-animation-play-state: paused; 
    -webkit-animation-play-state: paused; 
} 

/* PROGRESS BAR */ 
.progress-bar { 
    position: relative; 
    top: -5px; 
    width: 680px; 
    height: 5px; 
    background: #000; 
    -moz-animation: fullexpand 25s ease-out infinite; 
    -webkit-animation: fullexpand 25s ease-out infinite; 
} 
+0

Можете ли вы добавить больше описания того, к какому типу навигации вы стремитесь? Возможно, картина и попытка самой навигации? И вы хотите, чтобы он всегда переходил горизонтально или просто в какое-то время? –

+0

Да, я добавил pic, теперь вы можете видеть навигацию этого слайдера и, конечно же, переходы также, как вы можете видеть в jsfiddle, где я помещаю демонстрацию слайдера. –

+0

Я не вижу причин делать такие вещи в чистом CSS. Это чересчур многословное, трудноподдерживаемое и все другие плохие слова, которые вы можете себе представить. Что-то, что вы хотите сделать в 300 строках CSS, нуждается в менее чем 20 строках JS-jQuery –

ответ

0

Для прокрутки по горизонтали вы просто изменить top значения в анимации и #slider li в left с (скопировать его на слова и использования функция замены там), . Если вы хотите, чтобы прокрутить в другой стороне, вы можете изменить left с до right с, Demo of that

внешнего вида вы собираетесь использование кнопок «радио». Я не знаю, невозможно ли сделать то, что вы хотите, с чистым CSS, но это потребует каких-то сумасшедших манипуляций с анимацией.

С javascript это проще, но анимация CSS все еще затрудняет. По прошествии некоторого времени я придумал this solution (багги, посмотрите ниже для лучшего), который опирается на имена классов для анимаций.

После хорошей работы, я смог придумать решение, включающее переход к следующему изображению, which can be found here! Сейчас это довольно много работы, но я надеюсь, что комментарии облегчат понимание. Я не уверен, что вы можете сделать это в чистом CSS больше, ха-ха.

Javascript, который я написал, вероятно, может быть сокращен, я потратил слишком много времени, чтобы сделать его более эффективным. Единственная ошибка, которую я видел, - это короткое черное пространство при первом щелчке радио, и если вы нажимаете слишком быстро, иногда переход отсутствует. Надеюсь, это соответствует вашим потребностям!

Здесь добавлен код для окончательной версии найдены чуть выше:

/* Javascript */ 
// Obtain the objects within javascript to use 
var slider = document.getElementById('slider'), 
    one = document.getElementsByClassName('firstanimation')[0], 
    two = document.getElementsByClassName('secondanimation')[0], 
    three = document.getElementsByClassName('thirdanimation')[0], 
    four = document.getElementsByClassName('fourthanimation')[0], 
    five = document.getElementsByClassName('fifthanimation')[0], 
    // Hidden element that a 5s animation is applied to 
    hidden = document.getElementById('hidden'), 
    // Create an array of the li elements to make manipulating easier 
    liArray = [one, two, three, four, five], 
    // Obtain the radio buttons 
    radios = document.getElementsByName('picture'), 
    // For optimization and easy access later on 
    liNum = liArray.length, 
    // The bar at the bottom 
    progress = document.getElementById('progress-bar'), 
    // The li currently showing 
    currNum, 
    // Prefixes for the PrefixedEvent function 
    pfx = ["webkit", "moz", "MS", "o", ""]; 

// Give each radio button an onclick function 
for(var i = 0; i < liNum; i++) { 
    // The following line is necessary to prevent them all from being 5 
    radios[i].i = i; 
    radios[i].onclick = function() { changePic(this.i) }; 
} 

// Changes the radio every time a slide animates to the left 
PrefixedEvent(hidden, 'AnimationIteration', function() { 
    for(var i = 0; i < liNum; i++) { 
     // Checks to see which is checked 
     if(radios[i].checked) { 
      // Uncheckds the checked one 
      radios[i].checked = false; 
      // Checks the next one (first if there is no next one) 
      if(i + 1 < liNum) { 
       radios[i + 1].checked = true; 
      } else { 
       radios[0].checked = true; 
      } 
      break; 
     } 
    } 
}); 

// Makes using animationiteration easier cross-browser 
function PrefixedEvent(element, type, callback) { 
    for (var p = 0; p < pfx.length; p++) { 
     if (!pfx[p]) type = type.toLowerCase(); 
     element.addEventListener(pfx[p]+type, callback, false); 
    } 
} 

// Transitions from one slide to the clicked one, sets new animation order based on choice 
function changePic(nextNum) { 
    // Gets the li being displayed currently 
    for(var j = 0; j < liNum; j ++) { 
     var computedStyle = window.getComputedStyle(liArray[j]), 
      rightPos = computedStyle.getPropertyValue('right'); 
     if(rightPos == "0px") { 
      currNum = j; 
      break; 
     } 
    } 

    // Removes the animations for all the slider elements 
    one.className = ''; 
    two.className = ''; 
    three.className = ''; 
    four.className = ''; 
    five.className = ''; 
    hidden.className = ''; 
    progress.className = ''; 

    // Checks to see if it's a different element 
    if(nextNum != currNum) 
    { 
     // If it is, animate the new one in from the right, slide current to left 
     liArray[nextNum].style.right = "-685px";   
     liArray[currNum].style.right = "0px";   

     liArray[nextNum].style.right = "0px"; 
     liArray[currNum].style.right = "685px";   
    } else { 
     // If it's not, leave it 
     liArray[currNum].style.right = "0px"; 
    } 

    // Necessary to initialize another animation (known CSS flaw) 
    setTimeout(function() { 
     // Resets animation order based on the clicked radio 
     if(nextNum == 0) { 
      one.className = 'firstanimation'; 
      two.className = 'secondanimation'; 
      three.className = 'thirdanimation'; 
      four.className = 'fourthanimation'; 
      five.className = 'fifthanimation';  
      hidden.className = 'timer'; 
      progress.className = 'progress'; 
     } 
     if(nextNum == 1) { 
      one.className = 'fifthanimation'; 
      two.className = 'firstanimation'; 
      three.className = 'secondanimation'; 
      four.className = 'thirdanimation'; 
      five.className = 'fourthanimation';  
      hidden.className = 'timer'; 
      progress.className = 'progress'; 
     } 
     if(nextNum == 2) { 
      one.className = 'fourthanimation'; 
      two.className = 'fifthanimation'; 
      three.className = 'firstanimation'; 
      four.className = 'secondanimation'; 
      five.className = 'thirdanimation';  
      hidden.className = 'timer'; 
      progress.className = 'progress'; 
     } 
     if(nextNum == 3) { 
      one.className = 'thirdanimation'; 
      two.className = 'fourthanimation'; 
      three.className = 'fifthanimation'; 
      four.className = 'firstanimation'; 
      five.className = 'secondanimation'; 
      hidden.className = 'timer'; 
      progress.className = 'progress'; 
     } 
     if(nextNum == 4) { 
      one.className = 'secondanimation'; 
      two.className = 'thirdanimation'; 
      three.className = 'fourthanimation'; 
      four.className = 'fifthanimation'; 
      five.className = 'firstanimation';  
      hidden.className = 'timer'; 
      progress.className = 'progress'; 
     }   

     // Moves the previous image to the right with the rest 
     liArray[currNum].style.right = "-685px"; 

    }, 500 /* Transition length in milliseconds */); 
} 

/* Added HTML */ 
<!-- Under #slider and #mask... --> 
<li id="hidden" class='timer'></li> 

<!-- Under #content-slider... --> 
<nav id='photoNav'> 
    <input type="radio" name="picture" checked="true" id="navOne" /> 
    <input type="radio" name="picture" id="navTwo" /> 
    <input type="radio" name="picture" id="navThree" /> 
    <input type="radio" name="picture" id="navFour" /> 
    <input type="radio" name="picture" id="navFive" /> 
</nav> 

/* Added CSS */ 
#hidden { 
    visibility: hidden; 
    pointer-events:none;  
} 
#hidden.timer { 
    -mos-animation: nothing 5s linear infinite; 
    -webkit-animation: nothing 5s linear infinite; 
    animation: nothing 5s linear infinite; 
} 
#photoNav { 
    position: absolute; 
    top: 300px; 
    left:480px;  
    margin-left: -60px; 
    cursor:pointer; 
} 
#photoNav input { 
    cursor:pointer; 
} 
#progress-bar { 
    position:relative; 
    top:-5px; 
    width:680px; 
    height:5px; 
    background:#000; 
} 
#progress-bar.progress { 
    -moz-animation:fullexpand 25s ease-out infinite; 
    -webkit-animation:fullexpand 25s ease-out infinite; 
    animation:fullexpand 25s ease-out infinite; 
} 
@-moz-keyframes nothing { 0% {} 100% {} } 
@-webkit-keyframes nothing { 0% {} 100% {} } 
@keyframes nothing { 0% {} 100% {} } 

/* And some other smaller things not worth the space */ 

Излишне говорить, что было бы проще просто сделать это с JavaScript, но это была хорошая практика и весело делать, а

+0

, вы отлично поработали, но я ищу решение в чистом css, если кто-то сможет это сделать, это хорошо, :) Если ни один из вас не ответит, будет приемлемым :) –

+0

Чистое решение CSS близко, если не невозможно, если вы ищете какой-либо переход между слайдами при нажатии. Это так? –

+0

Можете ли вы добавить дополнительные кнопки с левой и правой стрелкой, обозначающей ползунок? –

0

Здесь у вас есть чистый слайдер CSS: https://github.com/drygiel/csslider

Если вы хотите автоматически изменять изображения, вы должны использовать CSS-анимацию для анимации левого края.

+0

Отличный :) хорошая работа. –

Смежные вопросы