عنصر شريحة JavaScript
-
25-09-2019 - |
سؤال
أريد أن أعرف ما هي أفضل تقنية لنقل عنصرًا كما هو الحال في هذه الأمثلة:
ولكن مع Pure Javascript
لذا NOT jQuery
أو أي مكتبة.
مثال بنية
<div id="holder">
<div id="bridge" onclick="slide('content')">Click to slide</div>
<div id="content" style="display:block;">The content</div>
</div>
لذلك إذا قمت بالنقر فوق id=bridge
ال id=content
إرادة slide up
ويضعه display
ل none
وإذا قمت بالنقر فوقه مرة أخرى ، فسيقوم بتعيينه display
ل block
و slides down
;
المحلول
يتم إجراء الرسوم المتحركة نفسها ، مثل كل الرسوم المتحركة في JavaScript ، باستخدام وظائف المؤقت: setTimeout
أو setInterval
. لتأثيرات بسيطة مثل هذا أنا أفضل دائما setTimeout
نظرًا لأنه من الأسهل إنهاء تسلسل الرسوم المتحركة مقارنة بـ setInterval
. كيف يعمل هو تغيير قيم السمات CSS باستخدام setTimeout
:
// move the content div down 200 pixels:
var content = document.getElementById('content');
function moveDown () {
var top = parseInt(content.style.marginTop); // get the top margin
// we'll be using this to
// push the div down
if (!top) {
top = 0; // if the margin is undefined, default it to zero
}
top += 20; // add 20 pixels to the current margin
content.style.marginTop = top + 'px'; // push div down
if (top < 200) {
// If it's not yet 200 pixels then call this function
// again in another 100 milliseconds (100 ms gives us
// roughly 10 fps which should be good enough):
setTimeout(moveDown,100);
}
}
هذا هو أساسا أساسيات الرسوم المتحركة في جافا سكريبت. الفكرة بسيطة للغاية. يمكنك استخدام أي سمة نمط CSS للرسوم المتحركة: أعلى واليسرى للعناصر الموقعة أو النسبية ، هوامش مثل مثال ، العرض ، الارتفاع ، الشفافية إلخ.
الآن ، أما بالنسبة لما يجب استخدامه في حالتك المحددة ، فإنك يعتمد بالضبط على ماهية نواياك. على سبيل المثال ، فإن أبسط شيء يجب أن تفعل ما تصفه هو تغيير ارتفاع DIV حتى يصبح صفرًا. شيء مثل:
function collapseContent () {
var height = parseInt(content.style.height);
if (!height) {
height = content.offsetHeight; // if height attribute is undefined then
// use the actual height of the div
}
height -= 10; // reduce height 10 pixels at a time
if (height < 0) height = 0;
content.style.height = height + 'px';
if (height > 0) {
// keep doing this until height is zero:
setTimeout(collapseContent,100);
}
}
ولكن هذا ليس كيف يفعل مكون jQuery Plugin. إنه يتراجع مثل أنه ينقل العنصر عن طريق تحويل سمة النمط العلوي واليسرى ويخفي الشاشة خارج المحتوى باستخدام حاوية div مع overflow:hidden
.
نصائح أخرى
يستخدم حلي انتقال CSS:
<style type="text/css">
#slider {
box-sizing: border-box;
transition: height 1s ease;
overflow: hidden;
}
</style>
<div id="slider" style="height: 0">
line 1<br>
line 2<br>
line 3
</div>
<script>
function slideDown(){
var ele = document.getElementById('slider');
ele.style.height = "3.3em";
// avoid scrollbar during slide down
setTimeout( function(){
ele.style.overflow = "auto";
}.bind(ele), 1000 ); // according to height animation
}
function slideUp(){
var ele = document.getElementById('slider');
ele.style.overflow = "hidden";
ele.style.height = "0";
}
</script>