>  기사  >  웹 프론트엔드  >  javascript 제어 가능한 투명 효과 구현 code_javascript 기술

javascript 제어 가능한 투명 효과 구현 code_javascript 기술

WBOY
WBOY원래의
2016-05-16 18:37:161042검색

CSS의 절대 위치 지정으로 인해 공간이 완전히 대체됩니다. 시작하기 전에 setTimeout(setInterval을 시뮬레이션하는 데 사용됨)의 재귀적 사용법을 연습해 보겠습니다.

코드 복사 코드는 다음과 같습니다.

함수 텍스트(el){
var node = (typeof el == "string")? document.getElementById(el) : el;
var i = 0;
varpeat = function(){
setTimeout(){
node .innerHTML = "

" i "

"
i
if(i <= 100){
setTimeout(arguments.callee, 100);
}
},100)
}
repeat();
}

가장 간단한 페이드인 효과인 노드를 변경해 보겠습니다. .innerHTML 라인을 투명도 설정에 추가합니다.
코드 복사 코드는 다음과 같습니다.

function fadeIn(el){
var node = (typeof el == "string")? document.getElementById(el) : el;
var i = 0;
var fade = function(){
setTimeout(){
! "v1"? (node.style.filter="alpha(opacity=" i ")"): (node.style.opacity = i / 100)
i
if(i < ;= 100 ){
setTimeout(arguments.callee, 100);
}
},100)
}
fade()
}

그러나 이것은 완벽하지 않습니다. 왜냐하면 IE의 필터가 IE7에서 작동하지 않을 수 있고 hasLayout을 활성화하려면 Zoom=1을 사용해야 하기 때문입니다. 사용자 정의 가능한 매개변수를 추가하여 확장해 보겠습니다. 댓글이 이미 매우 자세해서 이해가 안 되시면 메시지로 물어보세요.
코드 복사 코드는 다음과 같습니다.

함수 불투명도(el){
//필수 선택적 매개변수
var node = (typeof el == "string")? document.getElementById(el) : el,
//선택적 매개변수
options = 인수[1] || ,
//변경 기간
duration = options.duration || 1.0,
//처음의 투명성
from = options.from || 0.0,
//처음의 투명성 end
to = options.to || 0.5,
작업 = 1,
init = 0
if(to - from < 0){
작업 = -1,
init = 1;
}
//내부 매개변수
//setTimeout 실행 간격, 단위 밀리초
var 빈도 = 100,
//반복 호출 횟수 가정
count = 기간 * 1000 / 빈도,
// 각 투명도의 증분을 계산합니다
detal = Math.abs(to - from) /count,
// 진행 중인 작업 수
i = 0 ;
var main = function(){
setTimeout(function(){
if(! "v1"){
if(node.currentStyle.hasLayout) node.style.zoom = 1 ; //필터 실패 방지
node.style.filter="alpha(opacity=" (init * 100 Operation * detal * i * 100).toFixed(1) ")"
}else{
node.style.opacity = (init 작업 * detal * i).toFixed(3)
}
node.innerHTML = (init 작업 * detal * i).toFixed(3)
i
if(i <= 개수){
setTimeout(arguments.callee, 빈도)
}
},주파수)
}
main()

효과 시연 :


[Ctrl A 모두 선택 참고: 외부 J를 도입해야 하는 경우 실행하려면 새로 고쳐야 합니다. ]

< ;div class=" text" onclick="opacity(this,{duration:4.0,from:0.0,to:1})">


하지만 위 내용은 완벽하지 않아 버그가 있습니다. 우리는 기본 매개변수를 사용할지 아니면 전달하는 매개변수를 사용할지 결정하기 위해 단락 연산자를 사용하지만, 자바스크립트에서는 숫자 0 또는 심지어 0.0도 자동으로 false로 변환됩니다. 따라서 첫 번째 예에서 0을 전달하면 이 0을 사용하지 않고 기본값인 0.5를 사용합니다. 해결책은 문자열 "0"으로 만드는 것입니다. 또한 매개변수 i는 필요하지 않으며 생략하고 count를 사용하여 모든 루프를 담당할 수도 있지만 이 경우에는 생각이 바뀌게 됩니다. 덧셈으로 판명되었으므로 이를 뺄셈으로 변경하고 싶습니다.
코드 복사 코드는 다음과 같습니다.

function opacity(el){
//必选参数
var node = (typeof el == "string")? document.getElementById(el) : el,
//可选参数
options = arguments[1] || {},
//变化的持续时间
duration = options.duration || 1.0,
//开始时透明度
from = options.from || 0.0 ,
//结束时透明度
to = (options.to && options.to + "") || 0.5,
operation = -1,
init = 1;
if(to - from < 0){
operation = 1,
init = 0;
}
//内部参数
//setTimeout执行的时间,单位
var frequency = 100,
//设算重复调用的次数
count = duration * 1000 / frequency,
// 设算每次透明度的递增量
detal = operation * Math.abs(to - from) /count;
var main = function(){
setTimeout(function(){
if(!+"\v1"){
if(node.currentStyle.hasLayout) node.style.zoom = 1;//防止滤镜失效
node.style.filter="alpha(opacity="+ (init * 100 + detal * count * 100).toFixed(1) +")"
}else{
node.style.opacity = (init + detal * count).toFixed(3)
}
count--;
if(count + 1){
setTimeout(arguments.callee, frequency);
}
},frequency)
}
main();
}

进一步优化,利用原型共享方法。
复制代码 代码如下:

function Opacity(el){
var node = (typeof el == "string")? document.getElementById(el) : el,
options = arguments[1] || {},
duration = options.duration || 1.0,
from = options.from || 0.0 ,
to = (options.to && options.to + "") || 0.5,
operation = -1,
init = 1;
if(to - from < 0){
operation = 1,
init = 0;
}
var frequency = 100,
count = duration * 1000 / frequency,
detal = operation * Math.abs(to - from) /count;
this.main(node,init,detal,count,frequency);
}
Opacity.prototype = {
main : function(node,init,detal,count,frequency){
setTimeout(function(){
if(!+"\v1"){
if(node.currentStyle.hasLayout) node.style.zoom = 1;//防止滤镜失效
node.style.filter="alpha(opacity="+ (init * 100 + detal * count * 100).toFixed(1) +")"
}else{
node.style.opacity = (init + detal * count).toFixed(3)
}
node.innerHTML = (init + detal * count).toFixed(3)
count--;
if(count + 1){
setTimeout(arguments.callee, frequency);
}
},frequency)
}
}

演示代码:

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Extjs 연구 노트 1: Extjs에 대한 첫 소개: MessageBox_extjs다음 기사:Extjs 연구 노트 1: Extjs에 대한 첫 소개: MessageBox_extjs

관련 기사

더보기