是否有一种方法可以仅在 Google Chrome 中将以下 CSS 应用于特定的div
?
position:relative;
top:-2px;
是否有一种方法可以仅在 Google Chrome 中将以下 CSS 应用于特定的div
?
position:relative;
top:-2px;
我正在使用一个针对Chrome样式的Sass mixin,这是针对Chrome 29+
的解决方案,借鉴了上面Martin Kristiansson的方法。
@mixin chrome-styles {
@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm) {
@content;
}
}
使用方法如下:
@include chrome-styles {
.header { display: none; }
}
/* Find existing css selector
selectorName: selector name eg: ".myCssStyle"
*/
function cssFindSelector(selectorName){
//console.log( "document.styleSheets.length: "+document.styleSheets.length);
for(var i=0; i<document.styleSheets.length; i+=1){
var sheet = document.styleSheets[i];
for(var j=0; j<sheet.cssRules.length; j+=1){
var selTxt = sheet.cssRules[j].selectorText;
//console.log("selTxt:"+selTxt)
if (selTxt == selectorName){
return [i,j];
}
}
}
return null;
}
/* change existing css style
selectorName = existing css style to change ".myCssStyle"
newStyleStr = new style eg: "{color:red; border:1px;}"
*/
function cssChangeStyle(selectorName, newStyleStr){
var idx = cssFindSelector(selectorName)
if(idx == null){
return false;
}
var sheet = document.styleSheets[idx[0]];
sheet.deleteRule(idx[1]);
sheet.insertRule(selectorName+" "+newStyleStr,idx[1]);
return true;
}
function changeStyleFor_chrome(){
var txtUserAgent = navigator.userAgent;
////my mobile:
//navigator.userAgent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Mobile Safari/537.36
//my laptop:
//navigator.userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36
// iPhone from Mari:
//navigator.userAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 16_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1
//let n = txtUserAgent.search(/windows/i);
//let n = txtUserAgent.search(/iPhone/i);
let n = txtUserAgent.search(/Chrome/i);
let n2 = txtUserAgent.search(/iPhone/i);
if(n >= 0){
//console.log("agent chrome");
// here you shall put your style that you want to change for chrome
// note that style shall already exists!
var ret = cssChangeStyle(".myStyleChameleon", "{ color: red!important;}");
//console.log("ret: "+ret);
if(n2>0){
//chrom on iPhone
}
}
}
window.onload = changeStyleFor_chrome;
.myStyleChameleon {
color: green;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Change style by JavaScript only for Chrome</h2>
<div class="myStyleChameleon"> This text is GREEN for everything
except for Google Chrome where it is RED</div>
</body>
</html>
/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
/*your rules for chrome*/
#divid{
position:relative;
top:-2px;
}
}
看看这个,它对我有用。