【发布时间】:2021-06-21 22:09:33
【问题描述】:
是否可以在 iframe 中进行淡入淡出过渡?
【问题讨论】:
标签: javascript html
是否可以在 iframe 中进行淡入淡出过渡?
【问题讨论】:
标签: javascript html
淡入淡出可以通过随时间改变元素的不透明度来实现,一个非常简单的例子:
var iframe = document.getElementById('iframe');
fadeOut(iframe, 1000);
function fadeOut(el, duration) {
/*
* @param el - The element to be faded out.
* @param duration - Animation duration in milliseconds.
*/
var step = 10 / duration,
opacity = 1;
function next() {
if (opacity <= 0) { return; }
el.style.opacity = ( opacity -= step );
setTimeout(next, 10);
}
next();
}
虽然 jQuery 是一个令人难以置信的库,但您使用它的理由不仅仅是它能够创建精美效果的能力。应采用库的完整性和易用性;不是因为它恰好提供了您可能想要使用的一个东西。
【讨论】:
arguments.callee 在 javascript 中已被弃用,因此最好使用命名函数。 (我相应地编辑了您的答案)再次感谢!
if (opacity <= 0) { el.style.opacity = 0; return; } 否则你的不透明度可能会略高于 0.0
【讨论】:
或者,您可以让 CSS 为您处理这个问题。用很少的 javascript 来触发效果。
CSS:
#iframe_selector {
/* initial values for iframe, we'll change them via javascript. */
opacity: 0;
/* Note: In out/2016 opacity is on 97.39% of browsers */
/* Just an extra property to show multiple transitions, not needed for fade effect. */
height: 0;
/* Here you can handle a couple of transitions as you wish */
transition: opacity 2s ease-in-out, height 3s ease-in-out;
/* Note: Add all prefixes */
}
Javascript
function toogleIframe(iframe) {
//Check if is show with opacity property,
if (iframe.style.opacity == 0) {
//and set to original values,
iframe.style.opacity = 1;
iframe.style.height = '500px';
} else {
//or hide it.
iframe.style.opacity = 0;
iframe.style.height = '0px';
}
}
//And now, just use it...
//Examples:
domReady(function() {
toogleIframe(document.getElementById('iframe_selector'));
});
var button = document.getElementById('my_button');
button.onclick = function() {
toogleIframe(document.getElementById('iframe_selector'));
};
//Just specify when your iframe needs to be show or not...
只有一件事,也许您想在 iframe 将要显示时加载它,为此只需从 HTML 中的 iframe 中删除 src,然后使用 iframe.src 添加 JavaScript。这就是我的情况。
【讨论】:
您可以使用 onload 属性和 css 动画使 iframe 在加载后淡入
<iframe
src="..."
onload="this.style.opacity = '1';"
style="
opacity: 0;
transition-duration: 300ms;
transition-property: opacity;
transition-timing-function: ease-in-out;
"
></iframe>
【讨论】: