简体   繁体   中英

detect translate3d change like on scroll function with jQuery

I got a script that creates a smooth scrolling effect with removing the original browser scrollbar and changing the contents position with css translate3d . Now I want to include a script that detects that translate3d change to set a css rule on every scroll change. Here's my example code:

$(window).on('scroll', function() {
  $('myDiv').css('color', 'red').fadeOut('slow');
});

Now instead of calling .on('scroll', ...) i want to call something like .on('translate3dchange', ...) . Is there any way to achieve that?

Assuming the changes happen in the style attribute and not through css classes then you could use a MutationObserver but you would have to manually check if the changed property was the translate or which ever specific one you want.

 const test = document.querySelector('.test'); let counter = 0; // mimick an action altering the style of the .test element setInterval(function() { test.style.transform = `translate(${++counter}px)`; }, 500); //const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; const transformObserver = new MutationObserver(function(mutations) { const styleMutation = mutations[0]; const oldValue = styleMutation.oldValue.split(';').find(prop => prop.startsWith('transform') || prop.startsWith(' transform')); const current = styleMutation.target.style.transform; const old = ((oldValue && oldValue.split(':')[1]) || '').trim(); if (current !== old) { // the translate property has been changed // do what you want here console.log(current, old); } }); transformObserver.observe(test, { attributes: true, //configure it to listen to attribute changes attributeFilter: ['style'], //configure it to limit the listening only to the style attribute attributeOldValue: true // keep the old value so we can compare; }); 
 * { box-sizing: border-box } .test { width: 100px; height: 100px; border: 2px solid black; transform: translate(1px); } 
 <div class="test" style="background-image:url('somevalue');color:red;"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM