CSS转换没有在所有浏览器中使用jQuery进行更新

CSS transform not updating with jQuery in all browsers

本文关键字:jQuery 更新 浏览器 转换 CSS      更新时间:2023-09-26

我正在尝试翻译html范围输入滑块的input事件上的一个元素。但是当我检查元素时,jQuery创建的内联样式不会更新,而只是在转换中更新。我应用了一些伪样式,只是为了确保css正在更新,它们确实在更新。其他一切都按预期更新。

如果物品还没有被转换,那么它几乎可以工作一次。但在应用CSS转换后,它不会更新。我在Safari、Chrome和Firefox中进行了测试,结果相同。

方法如下:

useInputValues : function(){
    $('input[id$="-x"]').on('input', function(e){
        var id = $(this).parents('li').attr('data-item-id'),
            item = $('.grid [data-item-id="' + id + '"]'),
            x = $(this).val(),
            y = $(item).css('transform').split(',')[5] || 0,
            trans = 'translate(' + x + 'px, ' + y + 'px)';
            console.log(x + ", " + y); // this shows the values are correct and updating properly       
        // translate the element. Why doesn't this update each time?
        $(item).css('transform', trans); 
        // update the position attribute
        $(item).attr('data-x', x); // this happily updates in real time as expected
    })
},

进一步的上下文:在没有jQuery的情况下工作

我正在使用interact.js脚本,以便可以拖动项目以获得相同的效果。它使用的函数与我的非常相似,但它可以正常更新(没有jQuery)。

resizeMove : function(event){
    var target = event.target,
        x = (parseFloat(target.getAttribute('data-x')) || 0),
        y = (parseFloat(target.getAttribute('data-y')) || 0);
    target.style.width  = event.rect.width + 'px';
    target.style.height = event.rect.height + 'px';
    x += event.deltaRect.left;
    y += event.deltaRect.top;
    // Notice here: same general idea, but it's working
    target.style.webkitTransform = target.style.transform =
        'translate(' + x + 'px,' + y + 'px)';
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
    this.updateInputValues(target);
},

非常感谢您的帮助。

编辑:Fiddle

在这里看到它在做同样的事情:https://jsfiddle.net/d5kdmp0v/1/

获取transform样式的值将返回如下矩阵:

matrix(1, 0, 0, 1, 0, 0)

因为您在逗号上拆分这个字符串,所以结果的第6个元素的字符串中仍然有一个括号,所以字符串是0)。这是一个无效的CSS值。

如果你在拆分前去掉括号,你就会得到你所期望的:

y = $(item).css('transform').replace(')', '').split(',')[5] || 0

JSFiddle