Я делаю пользовательский фон параллакса JavaScript. На данный момент он отлично работает (как и предполагалось). К сожалению, я новичок в JavaScript, поэтому мои знания ограничены. Сценарий, который я написал, отлично работает, когда требуется только один экземпляр (так оно написано). Я хочу, чтобы он мог работать с несколькими экземплярами.JavaScript Параллакс Функция - Как создать несколько экземпляров
Прямо сейчас, он находит элемент с классом parallax
и делает его магическим. Очевидно, что так, как написано, наличие нескольких экземпляров/элементов класса «parallax» не будет работать. Я абсолютно зациклен на том, как сделать следующий шаг и применить свою функцию ко всем экземплярам отдельно. Я много искал, но до сих пор не знаю, как действовать. Код прилагается. В конце концов, я сделаю отдельную функцию для $(document).ready
, $(window).resize
и $(window).scroll
, чтобы сэкономить на вычислительной мощности, но я не хочу этого делать, пока не приблизиться к финишной линии.
Как я могу отформатировать этот скрипт для работы с несколькими экземплярами (несколько частей веб-страницы, которые будут использовать скрипт для эффекта)?
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0"/>
<title>Test Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
parallaxReady();
});
$(window).resize(function(){
parallaxReady();
});
$(window).scroll(function(){
parallaxReady();
});
function parallaxResize() {}
function parallaxScroll() {}
function parallaxReady() {
$(".parallax img").width('100%'); // This is for window resizing
$(".parallax img").height('auto'); // This is for window resizing
var winHeight = window.innerHeight; //
var offset = $(".parallax").offset(); //
var fromTop = offset.top; //
var scrollPos = window.pageYOffset; //
var ratio = -.7; // I would like to set this individually
var verticalAlign = 0; //
var travel = 0; //
var containerHeight = $(".parallax").css("height"); // Get container height
var containerWidth = $(".parallax").css("width"); // Get container width
containerHeight = parseInt(containerHeight, 10); // Remove px
containerWidth = parseInt(containerWidth, 10); // Remove px
var imageHeight = $(".parallax img").css("height"); // Get image height
var imageWidth = $(".parallax img").css("width"); // Get image width
imageHeight = parseInt(imageHeight, 10); // Remove px
imageWidth = parseInt(imageWidth, 10); // Remove px
if (winHeight > containerHeight){ // If the container is smaller than Viewport
travel = (winHeight - containerHeight); // Set travel distance
if (imageHeight < (containerHeight + (travel * -ratio))){ // If image is too short
$(".parallax img").height(containerHeight + (travel * -ratio) + 'px'); // Resize image to height needed
imageHeight = (containerHeight + (travel * -ratio)); // Update variable
$(".parallax img").width('auto'); // Set image width to auto
imageWidth = $(".parallax img").css("width"); // Update variable
imageWidth = parseInt(imageWidth, 10); // Remove px
}
else {
verticalAlign = (imageHeight - (containerHeight + (travel * -ratio))) // Else if image is tall enough, center it vertically
}
}
else { // Else if container is taller than Viewport
travel = (containerHeight) - winHeight; // Set travel distance
$(".parallax img").height(winHeight + (travel * -ratio) + 'px'); // Resize image to height needed
$(".parallax img").width('auto'); // Set image width to auto
imageWidth = $(".parallax img").css("width"); // Update variable
imageWidth = parseInt(imageWidth, 10); // Remove px
if (imageWidth < containerWidth){ // If image width is too short
$(".parallax img").width(containerWidth); // Set image width to 100% container width
$(".parallax img").height('auto'); // Set height to auto
verticalAlign = (imageHeight - (winHeight + (travel * -ratio))) // Center it vertically
}
}
if (imageWidth > containerWidth){ // If image width is wider than container
$(".parallax img").css('left',((imageWidth - containerWidth) * -.5) + 'px');// Center image horizontally
}
else { // Else if image is not wider than container
$(".parallax img").css('left','0'); // Reset to 0
}
var alignment = ((fromTop - winHeight) + containerHeight); // The initial height reference for image
var newPos = (scrollPos * ratio) - ((alignment * ratio) + (verticalAlign *.5)); // Position for Image based on our criteria
$(".parallax img").css('bottom',newPos + 'px'); // Set the new position for image
$("#debug").text("Scroll Height: " + scrollPos + " | Window Height: " + winHeight + " | DIV Height: " + containerHeight + " | Image Height " + imageHeight + " | Offset: " + fromTop + " | Travel: " + travel + " | Alignment: " + alignment + " | Vertical Align: " + verticalAlign);
}
</script>
<style scoped>
html, body {padding:0;margin:0;font-family:Arial, Helvetica, sans-serif;}
#debug {padding:15px;background:#000;font-size:12px;color:#fff;position:fixed;top:0;left:0;z-index:1000;opacity:.5;}
.spacer {height:70vh;background: #444;}
.longer {height:100vh;}
.parallax {overflow:hidden;position:relative;}
.parallax img {width:100%;position:absolute;bottom:0;}
.parallax div {width:40%;margin:10% auto;padding:5%;position:relative;color:#fff;font-size:36px;text-align:center;background:rgba(0,0,0,0.2);}
.parallax div p {padding:10px 0;margin:0;font-size:15px;text-align:justify;}
</style>
<div class="spacer"></div>
<div class="parallax">
<img alt="parallax" src="http://www.wallpaperup.com/uploads/wallpapers/2012/09/21/15744/3ad1c548edfc58f499feda5b042fb857.jpg">
<div>
This is Random Text
<p>Lorem ipsum dolor sit amet, mel id errem fierent sensibus, liber similique voluptatibus sit te, cum ea aliquip persequeris. Eam ne hinc labitur suscipit. Te laudem scaevola sea, esse nibh maiorum quo te. Sit enim regione ei, pro te accusamus definitiones. Maiorum perpetua oportere pro eu. Ea mel homero inermis insolens, ut adhuc putent qui.</p>
<p>Apeirian platonem interpretaris eu quo, wisi audire appetere sea ad. Vis cibo congue libris ut, has ea erat maiorum percipitur. Ius ut doming inciderint, affert eirmod cu sed. Ne mel falli partiendo, ei agam minim legimus sit. Quem omnis mundi pro in, ei viderer mediocritatem quo.</p>
</div>
</div>
<div class="spacer longer"></div>
<div id="debug"></div>
</body>
</html>
скрипьте свой код пожалуйста. – ProllyGeek
OP должен был его скриптировать, конечно, но, давайте, это просто заняло у меня 45 секунд, чтобы поиграть: http://jsfiddle.net/pabo/L2Lhz8vp/ – pabo