jquery 插件 css 不透明度
jquery plugin css opacity
我正在尝试为 CRT 类型效果创建一个简单的 jquery 插件。我确实检查了文档 -> https://learn.jquery.com/plugins/basic-plugin-creation/ 但我想我不明白。
当我执行代码而不将其转换为插件时,它工作正常。
setInterval(function(){
$('#wallpaper').css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
当我把它变成一个插件时,它什么都不做。
$.fn.crt = function(){
setInterval(function(){
$(this).css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
}
console.log($('#wallpaper').crt());
当我将 $(this).css()...
更改为 this.css()...
时,出现以下错误:TypeError: this.css is not a function
谁能告诉我如何让这段代码在插件中工作或者我做错了什么?
this
里面的timeout并不是你想的那样。它将是 window 对象。您需要 bind()
对此匿名函数或使用在外部定义变量的经典闭包技术。
$.fn.crt = function(){
var that = $(this);
setInterval(function(){
that.css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
}
我正在尝试为 CRT 类型效果创建一个简单的 jquery 插件。我确实检查了文档 -> https://learn.jquery.com/plugins/basic-plugin-creation/ 但我想我不明白。
当我执行代码而不将其转换为插件时,它工作正常。
setInterval(function(){
$('#wallpaper').css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
当我把它变成一个插件时,它什么都不做。
$.fn.crt = function(){
setInterval(function(){
$(this).css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
}
console.log($('#wallpaper').crt());
当我将 $(this).css()...
更改为 this.css()...
时,出现以下错误:TypeError: this.css is not a function
谁能告诉我如何让这段代码在插件中工作或者我做错了什么?
this
里面的timeout并不是你想的那样。它将是 window 对象。您需要 bind()
对此匿名函数或使用在外部定义变量的经典闭包技术。
$.fn.crt = function(){
var that = $(this);
setInterval(function(){
that.css("filter", "opacity("+ String(Math.random() * (0.96 - 1.0) + 0.96 ) +")");
}, (Math.random() * (500 - 1000) + 100) );
}