У меня есть функция JavaScript openWall();
, которая настроена на добавление класса в div
. Тем не менее, теперь я хотел бы отменить это действие. Я выполнил функцию closeWall();
, чтобы отменить это действие, однако я не знаю, как заставить div
его распознать.
Сценарий:
function openWall() {
var wall;
theWall = document.getElementById("wall");
theWall.className = "menu-responsive";
function closeWall() {
theWall.className = "";
}
}
И HTML:
<div class="hamburger">
<a href="#" onclick="openWall();">Menu</a>
</div>
<div id="wall"></div>
3 ответа
Вместо того, чтобы пытаться вызвать функцию openWall()
или closeWall()
при нажатии на элемент, просто используйте функцию toggleWall()
, чтобы открыть или закрыть соответствующий элемент на основе его текущего состояния; который может быть определен путем поиска имени класса, которое обозначает его открытое состояние (отсутствие этого имени класса означает, что стена не открыта). Итак, я бы предложил следующее:
function toggleWall() {
var theWall = document.getElementById('wall');
if (theWall.className.indexOf('menu-responsive') > -1) {
// indexOf returns -1 when the string is not found,
// therefore 'theWall' is found if the index is
// greater than -1; so 'theWall' is 'open', so here
// we close it:
theWall.className = theWall.className.replace('menu-responsive', '');
} else {
// the else here means that the string was not found,
// returning an index of -1 (or, technically, -1 or less;
// but indexOf only returns -1, 0 or positive indexes.
// so the string was not found, means the 'theWall' is
// 'closed' and so must be opened:
theWall.className = theWall.className + ' menu-responsive';
}
}
function toggleWall() {
var theWall = document.getElementById('wall');
if (theWall.className.indexOf('menu-responsive') > -1) {
theWall.className = theWall.className.replace('menu-responsive', '');
} else {
theWall.className = theWall.className + ' menu-responsive';
}
}
#wall {
background-color: red;
height: 4em;
}
#wall.menu-responsive {
background-color: limegreen;
}
#wall::before {
content: 'closed';
}
#wall.menu-responsive::before {
content: 'open';
}
<div class="hamburger">
<a href="#" onclick="toggleWall();">Menu</a>
</div>
<div id="wall"></div>
Или, используя немного более современный подход, вы можете просто использовать Element.classList.toggle()
для добавления или удаления заданного имени класса в зависимости от ситуации:
function toggleWall() {
var theWall = document.getElementById('wall');
theWall.classList.toggle('menu-responsive');
}
function toggleWall() {
var theWall = document.getElementById('wall');
// find out if the list of classes of the
// Element contains the class-name of
// 'menu-responsive' it's removed, and if
// it is not present then it's added:
theWall.classList.toggle('menu-responsive');
}
#wall {
background-color: red;
height: 4em;
}
#wall.menu-responsive {
background-color: limegreen;
}
#wall::before {
content: 'closed';
}
#wall.menu-responsive::before {
content: 'open';
}
<div class="hamburger">
<a href="#" onclick="toggleWall();">Menu</a>
</div>
<div id="wall"></div>
Кроме того, я настоятельно рекомендую вам отказаться от использования встроенных атрибутов HTML для привязки событий. Переключение на события, связанные с JavaScript, упрощает обслуживание и обновление без необходимости искать и заменять вызовы функций, разбросанные по всему источнику HTML. Тем не менее, я бы предложил использовать EventTarget.addEventListener()
для добавления обработчика событий:
document.querySelector('.hamburger > a[href="#"]')
.addEventListener('click', toggleWall);
function toggleWall() {
var theWall = document.getElementById('wall');
theWall.classList.toggle('menu-responsive');
}
// document.querySelector() returns the first
// HTML element matched by the CSS selector
// supplied as an argument; here it searches for
// an <a> element with a 'href' attribute equal
// to '#' which is the child of another element
// with the 'hamburger' class-name:
document.querySelector('.hamburger > a[href="#"]')
// binds the 'toggleWall()' function as the
// event-handler for the 'click' event:
.addEventListener('click', toggleWall);
function toggleWall() {
var theWall = document.getElementById('wall');
theWall.classList.toggle('menu-responsive');
}
#wall {
background-color: red;
height: 4em;
}
#wall.menu-responsive {
background-color: limegreen;
}
#wall::before {
content: 'closed';
}
#wall.menu-responsive::before {
content: 'open';
}
<div class="hamburger">
<a href="#">Menu</a>
</div>
<div id="wall"></div>
Убедитесь, что вы на самом деле вызываете функцию closeWall (), иначе код внутри не будет выполнен. Кроме этого, ваш код должен работать.
Кроме того, я бы предложил установить .className обратно на любое значение, которое было до изменения, сохранив это значение в переменной.
Вы можете попробовать что-то вроде ниже, чтобы переключить имя класса
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div class="hamburger">
<a href="#" onclick="toggleWall();">Menu</a>
</div>
<div id="wall"> wall </div>
<script>
function toggleWall() {
var wall;
theWall = document.getElementById("wall");
if(theWall.className ==="abc"){
theWall.className = "menu-responsive";
}else{
theWall.className = "abc";
}
}
</script>
</body>
</html>
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.