#javascript #html #css
#javascript #HTML #css
Вопрос:
Кто-нибудь может сказать, в чем ошибка в моем HTML-коде, я получаю ошибку «Неперехваченная ошибка типа: не удается прочитать свойство ‘getElementsByClassName’ с нулевым значением» во второй строке тега скрипта; var btns =… Также мой реализованный код активного заголовка не работает. Кнопка не становится активной после нажатия…
<style>
/* Style the buttons */
.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color:#7f9cf5;
cursor: pointer;
font-size: 1.125rem;
transform-style: inline-flex:;
color : white;
display: inline-flex;
border-radius: 0.25rem;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
background-color: #5a67d8;
color: white;
}
</style>
<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i ) {
btns[i].addEventListener("click", function actHeader() {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className = " active";
});
}
</script>
</head>
<body>
<header class="text-gray-700 body-font">
<div class="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
<a class="flex title-font font-medium items-center text-gray-900 mb-4 md:mb-0">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="w-10 h-10 text-white p-2 bg-indigo-500 rounded-full" viewBox="0 0 24 24">
<path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"></path>
</svg>
<a class="mr-5 hover:text-gray-900" href="/index">
<span class="ml-3 text-xl">{{ params['website_name'] }}</span>
</a>
</a>
<div class="shadow sm:shadow-md md:shadow-lg lg:shadow-xl xl:shadow-2xl" id="myDIV">
<nav class="md:ml-auto md:mr-auto flex flex-wrap items-center text-base">
<button class="btn"><a href="/">Home</a></button>amp;nbsp;amp;nbsp;
<button class="btn"><a href="/participate">Participate</a></button>amp;nbsp;amp;nbsp;
<button class="btn"><a href="/entries">Entries</a></button>amp;nbsp;amp;nbsp;
<button class="btn"><a href="/rules">Rules</a></button>amp;nbsp;amp;nbsp;<br>
<button class="btn"><a href="/result">Result</a></button>amp;nbsp;amp;nbsp;<br>
<button class="btn"><a href="/rewards">Rewards</a></button>amp;nbsp;amp;nbsp;<br>
<button class="btn"><a href="/contact">Contact</a></button>amp;nbsp;amp;nbsp;<br>
</nav></div>
</div>
Комментарии:
1. Скрипт выполняется до того, как страница будет отрисована. Поэтому нет никаких дел
myDIV
, когдаdocument.getElementById("myDIV");
, что называется, в результате чегоheader = null
. Оберните его в функцию и вызовите, когда тело загружено.2. То же самое для активных кнопок: кнопки не существуют на момент выполнения скрипта.
Ответ №1:
Как говорит Майкл, вы запускаете javascript слишком рано.
Самый простой способ решить эту проблему — поместить скрипт внизу страницы, непосредственно перед <body>
.
<html>
<head>
<title>title</title>
</head>
<body>
<!-- your page -->
<script type="text/javascript">
//your script
</script>
</body>
</html>