2014-09-17 4 views
1

Я написал несколько js, чтобы получить элемент по имени класса, но элемент, который я таргетинг, имеет два класса.Как использовать «getElementsByClassName» для получения нескольких классов из одного и того же элемента

<div class="module gh"> 

Это сценарий, который я использую, чтобы попытаться настроить этот класс.

var gh = document.getElementsByClassName("module gh"); 

По какой-то причине я получаю ошибку «неперехваченный TypeError: Невозможно установить свойство„-webkit-анимацию“неопределенный», который позволяет предположить, что класс не может быть найден. Что мне нужно сделать здесь?

Вот полный код, если кто-то хочет помочь мне очистить его и поделиться, почему они будут вносить изменения Я бы ВЕЛИКОЕ оценил это. Просто попасть в JS BTW ...

jQuery(document).ready(function(){jQuery('.carousel').each(function(index, element){jQuery(this)[index].slide = null;});jQuery('.carousel').carousel('cycle');}); 



var yPosition; 

window.onload = function(){ 

yPosition = document.getElementById("sp-menu-wrapper").offsetTop; 
} 

window.onscroll = function(){ 

var stickyMenu = document.getElementById("sp-menu-wrapper"); 
var userOneSlideIn = document.getElementById("sp-user1"); 
var userTwoSlideIn = document.getElementById("sp-user2"); 
var userThreeSlideIn = document.getElementById("sp-user3"); 
var userFourSlideIn = document.getElementById("sp-user4"); 
var gh = document.getElementsByClassName("gh"); 

if(document.getElementById("sp-user1") != null && document.getElementById("sp-user2") != null && document.getElementById("sp-user3") != null && document.getElementById("sp-user4") != null && yPosition <= (window.pageYOffset + -100)){ // compare original y position of element to y position of page 

    userOneSlideIn.style["-webkit-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-moz-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-os-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-ms-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style.marginLeft = "0px" 

    userTwoSlideIn.style["-webkit-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-moz-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-os-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-ms-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style.marginLeft = "30px" 

    userThreeSlideIn.style["-webkit-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-moz-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-os-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-ms-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style.marginLeft = "30px" 

    userFourSlideIn.style["-webkit-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-moz-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-os-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-ms-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style.marginLeft = "30px" 

} 

if(document.getElementById("sp-menu-wrapper") != null && yPosition <= window.pageYOffset){ 

    stickyMenu.style.position = "fixed"; 
    stickyMenu.style.top = "0px"; 
    stickyMenu.style.boxShadow= "rgb(112, 173, 139) 5px 5px 1200px"; 
    stickyMenu.style.width= "100%"; 
    stickyMenu.style.zIndex= "1"; 

}  

else{   

    stickyMenu.style.position = "inherit"; 
    stickyMenu.style.top = "";  
}      

if(document.getElementsByClassName("gh") != null && yPosition <= (window.pageYOffset + -400)){ 

    gh.style["-webkit-animation"] = "ffr 2s ease forwards"; 
    gh.style["-moz-animation"] = "ffr 2s ease forwards"; 
    gh.style["-os-animation"] = "ffr 2s ease forwards"; 
    gh.style["-ms-animation"] = "ffr 2s ease forwards"; 
    gh.style["animation"] = "ffr 2s ease forwards"; 
    gh.style.display = "block"; 

}    
} 

ПРИМЕЧАНИЕ: Вопрос был дан ответ, и вот мой модифицированный код для тех, кто имеет проблемы.

jQuery(document).ready(function(){//when document is ready - fire 

var yPosition;//yPosition variable. 

yPosition = document.getElementById("sp-menu-wrapper").offsetTop;// save original y position of element before scrolling. 

window.onscroll = function(){// on scroll this will fire. 

//declare all variables 
var stickyMenu = document.getElementById("sp-menu-wrapper"); 
var userOneSlideIn = document.getElementById("sp-user1"); 
var userTwoSlideIn = document.getElementById("sp-user2"); 
var userThreeSlideIn = document.getElementById("sp-user3"); 
var userFourSlideIn = document.getElementById("sp-user4"); 
var gh = document.querySelectorAll(".module.gh"); 

    //below - if element exists and scrlling is at this point - fire 
    if(document.getElementById("sp-user1") != null && document.getElementById("sp-user2") != null && document.getElementById("sp-user3") != null && document.getElementById("sp-user4") != null && yPosition <= (window.pageYOffset + -100)){ // compare original y position of element to y position of page 

     userOneSlideIn.style["-webkit-animation"] = "flyin1 1s ease forwards";//user1 style 
     userOneSlideIn.style["-moz-animation"] = "flyin1 1s ease forwards"; 
     userOneSlideIn.style["-os-animation"] = "flyin1 1s ease forwards"; 
     userOneSlideIn.style["-ms-animation"] = "flyin1 1s ease forwards"; 
     userOneSlideIn.style["animation"] = "flyin1 1s ease forwards"; 
     userOneSlideIn.style.marginLeft = "0px" 

     userTwoSlideIn.style["-webkit-animation"] = "flyin2 1s ease forwards";//user2 style 
     userTwoSlideIn.style["-moz-animation"] = "flyin2 1s ease forwards"; 
     userTwoSlideIn.style["-os-animation"] = "flyin2 1s ease forwards"; 
     userTwoSlideIn.style["-ms-animation"] = "flyin2 1s ease forwards"; 
     userTwoSlideIn.style["animation"] = "flyin2 1s ease forwards"; 
     userTwoSlideIn.style.marginLeft = "30px" 

     userThreeSlideIn.style["-webkit-animation"] = "flyin3 1s ease forwards";//user3 style 
     userThreeSlideIn.style["-moz-animation"] = "flyin3 1s ease forwards"; 
     userThreeSlideIn.style["-os-animation"] = "flyin3 1s ease forwards"; 
     userThreeSlideIn.style["-ms-animation"] = "flyin3 1s ease forwards"; 
     userThreeSlideIn.style["animation"] = "flyin3 1s ease forwards"; 
     userThreeSlideIn.style.marginLeft = "30px" 

     userFourSlideIn.style["-webkit-animation"] = "flyin4 1s ease forwards";//user4 style 
     userFourSlideIn.style["-moz-animation"] = "flyin4 1s ease forwards"; 
     userFourSlideIn.style["-os-animation"] = "flyin4 1s ease forwards"; 
     userFourSlideIn.style["-ms-animation"] = "flyin4 1s ease forwards"; 
     userFourSlideIn.style["animation"] = "flyin4 1s ease forwards"; 
     userFourSlideIn.style.marginLeft = "30px" 

    } 

    //below - if element exists and scrolling is at this point - fire 
    if(document.getElementById("sp-menu-wrapper") != null && yPosition <= window.pageYOffset){ 

     //sticky menu style 
     stickyMenu.style.position = "fixed"; 
     stickyMenu.style.top = "0px"; 
     stickyMenu.style.boxShadow= "rgb(112, 173, 139) 5px 5px 1200px"; 
     stickyMenu.style.width= "100%"; 
     stickyMenu.style.zIndex= "1"; 

    } 

    else{ 

     //always show 
     stickyMenu.style.position = "inherit"; 
     stickyMenu.style.top = ""; 
    } 

    //below - if element exists and scrolling is at this point - fire 
    if(document.querySelectorAll(".module.gh") != null && yPosition <= (window.pageYOffset + -400)){ 

     //loop through array 
     for(var g=0; g<gh.length; g++) { 
      gh[g].style["-webkit-animation"] = "ffr 2s ease forwards";//class="module gh" 
      gh[g].style["-moz-animation"] = "ffr 2s ease forwards"; 
      gh[g].style["-os-animation"] = "ffr 2s ease forwards"; 
      gh[g].style["-ms-animation"] = "ffr 2s ease forwards"; 
      gh[g].style["animation"] = "ffr 2s ease forwards"; 
      gh[g].style.display = "block"; 

     } 

    } 

} 

//fire carousel onload 
jQuery('.carousel').each(function(index, element){ 

    jQuery(this)[index].slide = null; 

}); 

jQuery('.carousel').carousel('cycle'); 

}); 
+4

Если 'jQuery' в коде [jQuery] (http://api.jquery.com/), зачем использовать собственные запросы DOM? – Teemu

+0

можете ли вы разместить html? – freshbm

+0

Прошу прощения, я не уверен, что вы имеете в виду. Не могли бы вы рассказать? – thaGH05T

ответ

2

У вас есть результат массива для:

var gh = document.getElementsByClassName("module gh"); 

, потому что у вас есть несколько дивы с class="module gh".

Вы должны написать что-то вроде этого в коде:

for(var i=0; i<gh.length; i++) { 
    gh[i].style ... 
} 

У меня есть пример кода здесь:

http://jsfiddle.net/j1tpkfa5/

или в вашем случае:

if(document.getElementsByClassName("gh") != null && yPosition <= (window.pageYOffset + -400)){ 
    for(var i=0; i<gh.length; i++) { 
     gh[i].style["-webkit-animation"] = "ffr 2s ease forwards"; 
     gh[i].style["-moz-animation"] = "ffr 2s ease forwards"; 
     gh[i].style["-os-animation"] = "ffr 2s ease forwards"; 
     gh[i].style["-ms-animation"] = "ffr 2s ease forwards"; 
     gh[i].style["animation"] = "ffr 2s ease forwards"; 
     gh[i].style.display = "block"; 
    }  
} 
+0

Отлично, я понимаю, что вы имеете в виду. Я сделаю это. Это будет проходить через каждую итерацию массива правильно? – thaGH05T

+0

Это работает для меня, спасибо за вашу помощь. – thaGH05T

1

использовать querySelectorAll вместо getElementsByClassName().

var gh = document.querySelectorAll(".module.gh"); 

Это вернет вам массив элементов. Вам нужно получить доступ к нему с помощью индекса eg., Gh [0] даст вам первый элемент. Проверьте JSFIDDLE.

проверка querySelectorAll

+0

Это не сработает, 'document.querySelectorAll (". Module.gh ")' будет, я полагаю, – KooiInc

+0

Я пробовал оба решения, используя 'document.querySelectorAll (" модуль gh ")' и 'document.querySelectorAll (". Module .gh ")' Те же ошибки. – thaGH05T

+0

Попробуйте обновленный код. –

1

getElementsByClassName использует имена классов CSS для идентификации элементов в документе ument, то есть он будет рассматривать атрибут класса каждого элемента. Элемент может иметь один или несколько классов CSS, например, в нашем примере, где у нас есть div с 2 классами module и gh. Используя селектор getElementsByClassName, вы можете выбрать элемент, используя любой из двух классов CSS или даже для обоих.

var el = document.getElementsByClassName('module gh'); 
console.log(el) 

здесь working version

+0

Правда, но в вашем примере у вас есть только один div с классом. У меня много (о чем я должен был упомянуть, думаю.) Но спасибо за ваши отзывы. – thaGH05T

+0

Этот код возвращает массив элементов с указанными именами классов. Вам нужно просто пройти через них. В любом случае, похоже, что вы ответили на свой вопрос. – Danis

1

Try и изменить это:

var gh = document.getElementsByClassName("module gh"); 

if(document.getElementsByClassName("gh") != null && yPosition <= (window.pageYOffset + -400)){ 
for(var k=0; k < gh.length; k++){ 

gh[k].style["-webkit-animation"] = "ffr 2s ease forwards"; 
gh[k].style["-moz-animation"] = "ffr 2s ease forwards"; 
gh[k].style["-os-animation"] = "ffr 2s ease forwards"; 
gh[k].style["-ms-animation"] = "ffr 2s ease forwards"; 
gh[k].style["animation"] = "ffr 2s ease forwards"; 
gh[k].style.display = "block"; 
} 
} 
+0

Похоже, он также будет работать как очень похожий, если не такой, как @freshmb. Я буду модифицировать и протестировать сейчас. – thaGH05T

+0

Это для меня очень спасибо за вашу помощь. – thaGH05T

2

Согласно W3C HTML5 Specification, ваш метод должен работать. Кроме того, помните, что использование document.getElementsByClassName() с неизвестным именем класса возвращает пустой массив, поэтому он никогда не null (см. Ваш последний if).

Комментарий Teemu относится к JQuery, но учитывая, что вы новичок в JS, это не имеет большого значения.

Однако, я вижу, что ваш JS выполняется как можно скорее, когда загружается веб-страница, поэтому, если ваш JS пытается помешать элементам HTML, которые еще не созданы, вы получаете сообщение об ошибке.

Первая строка кода, которую вы видите, выполняется, когда DOM готов, когда все элементы созданы; по крайней мере, я мог бы вам посоветовать поставить ваш window.onscroll внутри первой глубины кода JQuery и window.onload до окна. Прокрутка в JQuery.

Я даю вам совет:

jQuery(document).ready(function(){ 
    //You can create your yPosition variable here because it will be used only inside this function. 

    //Then you can put the window.onload content here (only inside the function, since JQuery(document).ready() is doing the same thing as window.onload) 

    // And here you can write your window.onscroll 


    jQuery('.carousel').each(function(index, element){ 
    jQuery(this)[index].slide = null; 
    }); 
    jQuery('.carousel').carousel('cycle'); 
}); 


var yPosition; 

window.onload = function(){ 

yPosition = document.getElementById("sp-menu-wrapper").offsetTop; 
} 

window.onscroll = function(){ 

var stickyMenu = document.getElementById("sp-menu-wrapper"); 
var userOneSlideIn = document.getElementById("sp-user1"); 
var userTwoSlideIn = document.getElementById("sp-user2"); 
var userThreeSlideIn = document.getElementById("sp-user3"); 
var userFourSlideIn = document.getElementById("sp-user4"); 
var gh = document.getElementsByClassName("gh"); 

if(document.getElementById("sp-user1") != null && document.getElementById("sp-user2") != null && document.getElementById("sp-user3") != null && document.getElementById("sp-user4") != null && yPosition <= (window.pageYOffset + -100)){ // compare original y position of element to y position of page 

    userOneSlideIn.style["-webkit-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-moz-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-os-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["-ms-animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style["animation"] = "flyin1 1s ease forwards"; 
    userOneSlideIn.style.marginLeft = "0px" 

    userTwoSlideIn.style["-webkit-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-moz-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-os-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["-ms-animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style["animation"] = "flyin2 1s ease forwards"; 
    userTwoSlideIn.style.marginLeft = "30px" 

    userThreeSlideIn.style["-webkit-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-moz-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-os-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["-ms-animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style["animation"] = "flyin3 1s ease forwards"; 
    userThreeSlideIn.style.marginLeft = "30px" 

    userFourSlideIn.style["-webkit-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-moz-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-os-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["-ms-animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style["animation"] = "flyin4 1s ease forwards"; 
    userFourSlideIn.style.marginLeft = "30px" 

} 

if(document.getElementById("sp-menu-wrapper") != null && yPosition <= window.pageYOffset){ 

    stickyMenu.style.position = "fixed"; 
    stickyMenu.style.top = "0px"; 
    stickyMenu.style.boxShadow= "rgb(112, 173, 139) 5px 5px 1200px"; 
    stickyMenu.style.width= "100%"; 
    stickyMenu.style.zIndex= "1"; 

}  

else{   

    stickyMenu.style.position = "inherit"; 
    stickyMenu.style.top = "";  
}      

if(document.getElementsByClassName("gh") != null && yPosition <= (window.pageYOffset + -400)){ 

    gh.style["-webkit-animation"] = "ffr 2s ease forwards"; 
    gh.style["-moz-animation"] = "ffr 2s ease forwards"; 
    gh.style["-os-animation"] = "ffr 2s ease forwards"; 
    gh.style["-ms-animation"] = "ffr 2s ease forwards"; 
    gh.style["animation"] = "ffr 2s ease forwards"; 
    gh.style.display = "block"; 

}    
} 

Может быть, я повторяюсь, но не забывайте, что document.getElementsByClassName() возвращает массив HTMLElement, не только HTMLElement (вид s после Element в getElementsByClassName())

Я надеюсь, что я помог вам.

+0

Очень я буду учитывать это и очищать код. Я понимаю «s», поскольку я пытался получить все элементы, но не знал, что мне нужно применять стили CSS для каждой итерации в массиве. Надеюсь, я прояснился. – thaGH05T

+0

Вы очень понятны. – Magador

+0

ОК, теперь я переделал сценарий и понял, почему вы внесли свои предложения. Нагрузка на самом деле быстрее и намного более гладкая, благодаря чему вам нужно пройти лишнюю милю! Я напишу свой рабочий код в своем вопросе, чтобы все могли его увидеть. – thaGH05T

1

Хорошо, ответ на этот конкретный вопрос лучше всего ответил @freshbm и @Fraizan. Они сказали мне использовать цикл for для прохождения каждой итерации массива, который был создан document.querySelectorAll. Это то, что я сделал, чтобы изменить код.

if(document.querySelectorAll("module gh") != null && yPosition <= (window.pageYOffset + -400)){ // compare original y position of element to y position of page 

    for(var g=0; g<gh.length; g++) { 
    gh[g].style["-webkit-animation"] = "ffr 2s ease forwards"; 
    gh[g].style["-moz-animation"] = "ffr 2s ease forwards"; 
    gh[g].style["-os-animation"] = "ffr 2s ease forwards"; 
    gh[g].style["-ms-animation"] = "ffr 2s ease forwards"; 
    gh[g].style["animation"] = "ffr 2s ease forwards"; 
    gh[g].style.display = "block"; 
    } 
} 

Это работало отлично, чтобы решить мою проблему.

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