Как создать плавный эффект появления блоков справа и слева в jQuery
В jQuery нет таких методов, как slideLeft()
и slideRight()
, похожих на slideUp()
и slideDown()
, но вы можете имитировать эти эффекты с помощью jQuery-метода animate()
.
Давайте посмотрим на следующий пример, чтобы понять, как это работает:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery slideLeft and slideRight Effect</title>
<style>
.box{
float:left;
overflow: hidden;
background: #f0e68c;
}
/* Добавляем отступ и границу к внутреннему содержимому
для лучшего эффекта анимации */
.box-inner{
width: 400px;
padding: 10px;
border: 1px solid #a29415;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
var boxWidth = $(".box").width();
$(".slide-left").click(function(){
$(".box").animate({
width: 0
});
});
$(".slide-right").click(function(){
$(".box").animate({
width: boxWidth
});
});
});
</script>
</head>
<body>
<button type="button" class="slide-left">Slide Left</button>
<button type="button" class="slide-right">Slide Right</button>
<hr>
<div class="box">
<div class="box-inner">Lorem ipsum dolor sit amet...</div>
</div>
</body>
</html>
Есть еще лучший способ создать этот эффект. В следующем примере ползунок переключает поле right-to-left и left-to-right, что-то вроде эффекта slideToggle()
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Slide Left and Right Toggle Effect</title>
<style>
.box{
float:left;
overflow: hidden;
background: #f0e68c;
}
/* Добавляем отступ и границу к внутреннему содержимому
для лучшего эффекта анимации */
.box-inner{
width: 400px;
padding: 10px;
border: 1px solid #a29415;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$(".slide-toggle").click(function(){
$(".box").animate({
width: "toggle"
});
});
});
</script>
</head>
<body>
<button type="button" class="slide-toggle">Slide Toggle</button>
<hr>
<div class="box">
<div class="box-inner">Lorem ipsum dolor sit amet...</div>
</div>
</body>
</html>