我正在尝试创建一个简单的插件
下面的代码在header属性中添加每个样式标记。样式标签包含CSS动画,动画名称为animate
(function( $ ) {
$.fn.plugin = function( options ) {
this.each(function() {
var keyFrames = "@keyframes animate {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
$("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
});
return this;
};
}( jQuery ));
$( ".animation" ).plugin({});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<div class="animation">dsdsd</div>
</body>
</html>
但我试着让它每次都添加一个不同的动画名称。例如不起作用
(function( $ ) {
$.fn.plugin = function( options ) {
this.each(function() {
var counter = 1;
var keyFrames = "@keyframes animate" + counter++ " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
$("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
});
return this;
};
}( jQuery ));
$( ".animation" ).plugin({});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<div class="animation">dsdsd</div>
</body>
</html>
当您运行代码时,您会看到有一个Uncaught SyntaxError: Unexpected string.
。这是您关于实际查找位置(使用字符串的某个位置(的第一条线索。
如果你看这行:var keyFrames = "@keyframes animate" + counter++ " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
,你的问题是你有counter++
,但之后不要连接任何东西。您的代码应该如下:
(function( $ ) {
$.fn.plugin = function( options ) {
this.each(function() {
var counter = 1;
var keyFrames = "@keyframes animate" + counter++ + " {0%{transform:translate3d(0,0,0)}100%{transform:translate3d(-250px,0,0)}}";
$("<style type='text/css'>" + keyFrames + "</style>").appendTo($("head"));
});
return this;
};
}( jQuery ));
$( ".animation" ).plugin({});
<html>
<body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <div class="animation">dsdsd</div> </body> </html>