我正在寻求帮助,因为我不能像我想的那样修复这个javascript。基本上,我想添加"打字机"类。到id "textanimation"鼠标悬停,然后移除。
其余的工作,在某种意义上,我正确地购买了具有描述性文本和照片的div。谢谢你的建议
https://codepen.io/bastia-g5/pen/LYgPGNp
$(document).ready(function() {
$('h1').hover(function(){
var element = document.getElementById("textanimation");
element.classList.add("typewriter");
$('#d'+$(this).prop('id')).show();
}, function() {
var element = document.getElementById("textanimation");
element.classList.remove("typewriter");
$('#d'+$(this).prop('id')).hide();
});
});
.first {
display:none;
}
.hover_img {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="sectionhome">
<div class="row verticalalign">
<div class="col">
<div>
<h1 id="firstdiv">Brand</h1>
</div>
<div class="hover_img" id="dfirstdiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
<img src="https://picsum.photos/200/300">
</div>
<div>
<h1 id="seconddiv">Servizi</h1>
</div>
<div class="hover_img" id="dseconddiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
<img src="https://picsum.photos/200/300">
</div>
<div>
<h1 id="thirddiv">B2B</h1>
</div>
<div class="hover_img" id="dthirddiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
<img src="https://picsum.photos/200/300">
</div>
</div>
</div>
</section>
您的代码不工作,因为您有多个ID为textanimation
的元素,但HTML ID必须是唯一的。这意味着var element = document.getElementById("textanimation");
总是返回具有该ID的第一个元素。相反,使用一个类来选择所需的元素,并使用jQuery的.find
将搜索限制为显示的<div>
的子元素:
$(document).ready(function() {
$('h1').hover(function() {
const id = $(this).attr('id');
const containerId = `d${id}`;
$(`#${containerId}`)
.show()
.find('.subtitle').toggleClass('typewriter', true)
;
}, function() {
const id = $(this).attr('id');
const containerId = `d${id}`;
$(`#${containerId}`)
.hide()
.find('.subtitle').toggleClass('typewriter', false)
;
});
});
.first {
display: none;
}
.hover_img {
display: none;
}
.typewriter {
border: 2px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="sectionhome">
<div class="row verticalalign">
<div class="col">
<div>
<h1 id="firstdiv">Brand</h1>
</div>
<div class="hover_img" id="dfirstdiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
</div>
<div>
<h1 id="seconddiv">Servizi</h1>
</div>
<div class="hover_img" id="dseconddiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
</div>
<div>
<h1 id="thirddiv">B2B</h1>
</div>
<div class="hover_img" id="dthirddiv">
<p id="textanimation" class="subtitle">There are many variations of passages of Lorem Ipsum available</p>
</div>
</div>
</div>
</section>