javascript - 用 JS 显示一个随机的 css Sprite
问题描述
我有一个当前脚本,它显示来自 200-300 个文件名数组的随机图标。这行得通。
我对独立的文件/应用程序产生了新的兴趣。
我可以从 css 精灵表中选择一个随机精灵并使用 js 或 jQuery 在按下按钮时显示它吗?
我不是在这里寻找完整的代码......只是对这将带来什么的一般概念。
解决方案
这就是我将如何处理它。如果您有一个带有不同精灵的精灵表。您使用 JS 向其附加不同的类,它们都代表精灵表中的不同位置
<style>
img_1{
width:120px;
height:123px;
background-image:url('Images/newcampaign_sprite2.png');
background-position:0px 0px;
}
img_2{
width:120px;
height:123px;
background-image:url('Images/newcampaign_sprite2.png');
background-position:10px 10px;
}
</style>
<body>
<img id='foo1'>
<script>
//Initiate the variables
let random = Math.floor(Math.random() * 3) + 1 ;
let classwithSpritePos ='';
//check what random is between 1-3 and apply the sprite position class
if(random == 1){classwithSpritePos = 'img_1'; }
if(random == 2){classwithSpritePos = 'img_2'; }
let img = document.getElementById('foo1');
img.classList.add(classwithSpritePos);
</script>
推荐阅读
- javascript - 如何使用 Nodejs 将文本文件中的内容添加到字典中?
- python - pip:忽略对--force-reinstall的依赖项的依赖项
- r - 在 R Shiny 中,如何编写一个在单击操作按钮时生成额外用户输入的函数?
- sql - 如果存在特定行类型,则从特定行选择行到最新行
- javascript - 用于检查 Excel 工作表名称的无效字符的 JavaScript 正则表达式
- flutter - 在 Flutter 故事视图中设置视频时长
- php - Wordpress 重定向做错了
- breadcrumbs - 摩纳哥编辑面包屑
- plot - 在 MATLAB R2015b 中绘制阴影条形图时出现错误“未定义的函数或变量 'applyhatch_plusC'”
- performance - 如何在 GtMetrix 中修复错误(失败)net::ERR_HTTP2_SERVER_REFUSED_STREAM