javascript - 单击时循环遍历 3 个 CSS 阶段

标签 javascript jquery

我试图做到这一点,以便当单击任何字母时,它都会进入下一个“阶段”。第一个是不透明度 = 1 和黑色,第二个不透明度 = 0.2。第三个它变成蓝色,不透明度 = 1。我在 google chrome 上遇到它变成蓝色和不透明度回到 1 的问题,我什至无法在 jsfiddle 上得到不透明度 = .2。我脑子里确实有 jquery 颜色插件,

<script type="text/javascript"src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/color/jquery.color-2.1.0.js"></script>

我的 JavaScript 有点粗糙,所以我假设那里有问题。

这里是 https://jsfiddle.net/tombatan/jLu4kLwo/1/

    $(document).ready(function () {
    $('.alphabetLetter').click(function () {
        if ($(this).css('opacity') == '1' && $(this).css('color') == '#414141') {
            $(this).animate({
                opacity: 0.2
            }, 250);
        } else if ($(this).css('opacity') == '0.2') {
            $(this).animate({
                color: '#145ECF',
                opacity: 1
            }, 250);
        } else {
            $(this).animate({
                color: '#414141'
            }, 250);
        }
    });
});

有人知道这是怎么回事吗?

最佳答案

这里有一些问题,首先:

if ($(this).css('opacity') == '1' && $(this).css('color') == '#414141') {

这应该检查 #000000,而不是 #414141

其次,$(this).css('color') 返回 rgb 值,而不是十六进制。

if ($(this).css('opacity') == '0.2')

这将不匹配,因为 jQuery.css('opacity') 将返回一个浮点值,例如 0.20000000035,它不等于 0.2.

最后你想在最后的 else 中改回 #000000

你可以这样做:

$(document).ready(function () {
    $('.alphabetLetter').click(function () {
        if ($(this).css('opacity') == '1' && $(this).css('color') == 'rgb(0, 0, 0)') {
            $(this).animate({
                opacity: 0.2
            }, 250);
        } else if (Math.round(100 * parseFloat($(this).css('opacity'))) / 100 == 0.2) {
            $(this).animate({
                color: '#145ECF',
                opacity: 1
            }, 250);
        } else {
            $(this).animate({
                color: '#000000'
            }, 250);
        }
    });
});

我已经更新了你的 fiddle :https://jsfiddle.net/jLu4kLwo/7/

关于javascript - 单击时循环遍历 3 个 CSS 阶段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31662361/

相关文章:

javascript - 下拉菜单作为一个 block

javascript - 我可以将参数传递给客户端 HTML 页面吗?

jquery - 如何处理两个重叠的 Twitter Bootstrap 模态

php - 在完整网页中打印网页

javascript - 定义自定义事件

javascript - 无法重现 TypeError : 'undefined' is not an object

javascript - jqxValidator,禁用验证错误时的自动滚动

javascript - 获取 div 标签下的表格数量

固定列中的 jQuery DataTables 复选框

javascript - 在 iOS/Android 上的 HTML5 混合应用程序中持久存储的可靠方法