Answer the question
In order to leave comments, you need to log in
Change style with javascript
Who can tell how to solve the problem
there are 5 div blocks, each with its own id and b-img style
<div id="1" class="b-img" onclick="kodimg(id)">...</div>
<div id="2" class="b-img" onclick="kodimg(id)">...</div>
<div id="3" class="b-img" onclick="kodimg(id)">...</div>
<div id="4" class="b-img" onclick="kodimg(id)">...</div>
<div id="5" class="b-img" onclick="kodimg(id)">...</div>
function kodimg(id)
{
document.getElementById(id).className = 'v-img';
}
Answer the question
In order to leave comments, you need to log in
1 option. Store the id of the previous clicked in a (global) variable.
var old_id; function kodimg(id) { if (old_id) document.getElementById(old_id).className = 'b-img'; document.getElementById(id).className = 'v-img'; old_id = id; }
function kodimg(id) { for (var i = 1; i <= 5; i++) document.getElementById(i).className = 'b-img'; document.getElementById(id).className = 'v-img'; }
Let's start with the fact that since we are talking about switching classes, it is appropriate to write all the styles in CSS at once:
.bImg { /* сюда вписываем стиль обычного div */ }
.vImg { /* сюда вписываем стиль div, жмякнутого мышою */ }
For <div> elements , it is enough to specify classes after that <div id="1" style="b-img" onclick="kodimg(id)">...</div>
<div id="2" style="b-img" onclick="kodimg(id)">...</div>
<div id="3" style="b-img" onclick="kodimg(id)">...</div>
<div id="4" style="b-img" onclick="kodimg(id)">...</div>
<div id="5" style="b-img" onclick="kodimg(id)">...</div>
<div class="bImg">...</div>
<div class="bImg">...</div>
<div class="bImg">...</div>
<div class="bImg">...</div>
<div class="bImg">...</div>
$(function(){
// после загрузки документа назначаем обработчики событий:
$('div.bImg').click(function(){
// в обработчике делаем две вещи:
// 1) находим предыдущий жмякнутый div, отменяем жмякнутость
$('div.vImg').removeClass('vImg').addClass('bImg');
// 2) свежежмякнутому div придаём жмякнутость
$(this).removeClass('bImg').addClass('vImg');
});
});
Something like this:
for (var i = 1; i <= 5; i++) { if (id == i) { document.getElementById(i).className = 'v-img'; } else { document.getElementById(i).className = 'b-img'; } }
onclick="kodimg(this)" var lastcodedimg=0; function kodimg(_this) { if(lastcodedimg){ lastkodimg.className='bimg' } _this.className='v-img'; lastcodedimg=_this; }
...
...
...
...
...
function kodimg(element){
document.querySelector('.current').classList.remove('current');// current is the class for the selected element
element. classList.add('current');
}
You messed up in the task, write about styles. it's about classes. An example for firefox, by analogy, you can do it for other browsers.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question