使用javascript动态更改CSS类属性

问题描述 投票:0回答:2

我具有由第三方Js应用程序更改的变换属性的div,我想要的是根据其当前的变换属性在某些情况下修复变换属性。

为此,如果第三方应用程序对元素样式的任何更改无效,则需要在此处添加具有属性transform: current_transform!important的类和!important

这里我创建了一个示例片段以进行更好的解释

//let this is third party app which is changing the paragraph width and html which code can't be manipulated
function changeHeight(e) {
  var x = e.clientX;
  var y = e.clientY;
  $('p').html(y);
  $('p').css('width',x+"px");
}

// Here we need to write Js code so that any change in paragraph css will not be effective, if zoom is yes

$('[name="zoom"]').on('change',function(){
  if($(this).val()=='y'){
    // Here need to change to the .zoomed propery as widht: current_width!improtant so that paragraph width get fixed to lastly it have.
    
    $('p').addClass('zoomed');
  }
  else{
    $('p').removeClass('zoomed');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
  .zoomed{
    width: 50px!important;
  }
 </style>
<label>zoom yes</label>
<input type="radio" name="zoom" value="y" />
<label>zoom no</label>
<input type="radio" name="zoom" value="n" checked/>

<div style="height:70px;border:1px solid #000000;" onmousemove="changeHeight(event)">
</div>
<p style="background-color:red;"></p>

这仅是示例,实际情况有所不同(关于转换属性和缩放),但是关键是动态更改类属性,以使第三方更改样式无效。

javascript jquery html css dom
2个回答
0
投票

//let this is third party app which is changing the paragraph width and html which code can't be manipulated function changeHeight(e) { var x = e.clientX; var y = e.clientY; $('p').html(y); $('p').css('width',x+"px"); } // Here we need to write Js code so that any change in paragraph css will not be effective, if zoom is yes let styleOverride = document.querySelector('#styleOverride'); if (!styleOverride) { styleOverride = document.createElement('style'); styleOverride.id = 'styleOverride'; document.body.appendChild(styleOverride); } styleOverride.innerHTML = ''; $('[name="zoom"]').on('change',function(){ if($(this).val()=='y'){ // Here need to change to the .zoomed propery as widht: current_width!improtant so that paragraph width get fixed to lastly it have. let wid= $('p').css('width')+"!important"; styleOverride.innerHTML = ` .zoomed{ width: ${wid}; } `; $('p').addClass('zoomed'); } else{ $('p').removeClass('zoomed'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> .zoomed{ width: 50px!important; } </style> <label>zoom yes</label> <input type="radio" name="zoom" value="y" /> <label>zoom no</label> <input type="radio" name="zoom" value="n" checked/> <div style="height:70px;border:1px solid #000000;" onmousemove="changeHeight(event)"> </div> <p style="background-color:red;"></p>

-1
投票
© www.soinside.com 2019 - 2024. All rights reserved.