var slideList = this.getElementsByTagName("ul")[0];
Javascript sliding menus not working
-
01-06-2022 - |
質問
This javascript sliding menu is NOT working--the only error that debugger gives is that the first IF statement is a block command & should have curly braces, which I don't understand.
Does anyone see an obvious error? I'm not sure I'm using 'this' keyword correctly( as well as the variable slideList inside the function showSlide...please help & any feedback on my formatting (white-space) is appreciated as well!
window.onload = makeMenus;
var currentSlide = null;
var timeID = null;
var leftPos = 0;
function makeMenus() {
var slideMenus = new Array();
var allElems = document.getElementsByTagName("*");
for (var i = 0; i < allElems.length; i++) {
if (allElems[i].className == "slideMenus") menus.push(allElems[i]);
}
for (var i = 0; i < slideMenus.length; i++) {
slideMenus[i].onclick = showSlide;
slideMenus[i].ul.style.left = "0px"; //for each object in slideMenus Array, ref 1st ul element within that object and set the value of the ul elements left style property to 0px
}
document.getElementById("head").onclick = closeSlide;
document.getElementById("main").onclick = closeSlide;
}
function showSlide() {
var slideList = this.id + ".ul[0]"; //stores object ref to the 1st ul element nested within the current object.
if (currentSlide !== null) {
closeSlide();
} else {
closeSlide();
currentSlide = slideList;
currentSlide.style.display = "block";
timeID = setInterval("moveSlide()", 1);
}
}
function closeSlide() {
if (currentSlide !== null) {
clearInterval(timeID);
currentSlide.style.left = "0px";
currentSlide.style.display = "none";
currentSlide = null;
}
}
function moveSlide() {
if ((leftPos + 5) <= 220) {
currentSlide.style.left = leftPos + "px"
} else {
clearInterval(timeID);
leftPos = 0;
}
}
解決 2
他のヒント
just taking a look at your code I noticed that you have this line
var slideList = this.id + ".ul[0]"; //stores object ref to the 1st ul element nested
It looks like you're trying to grab the first element of the ul array, but since you're putting that in quotes your browser is likely treating that like a string instead. Say this.id was equal to the string "ul-element", this variable will output "ul-element.ul[0]" as a string rather than getting the element at ul[0].
Just out of curiosity, have you looking into using jquery to make your site do this? It would save quite a bit of time and headache, although if you're doing this for a personal project I understand doing it this way :)
-Frank