Tôi đang phát triển trang web trong môi trường trình duyệt web hỗn hợp (Chrome/IE11). IE11 không hỗ trợ các biến CSS, là có một polyfill hoặc kịch bản tồn tại mà sẽ cho phép tôi sử dụng các biến CSS trong IE11?IE11 - hiện một tập lệnh/tập lệnh có tồn tại cho các biến CSS không?
Trả lời
+1 cho liên kết đoạn mã-mã trong phần bình luận câu hỏi ở trên bởi [Tôi có kode]. Một điều tôi tìm thấy mặc dù là đoạn mã cần phải được sửa đổi một chút để có các khai báo hàm được định nghĩa trong định dạng JSON cho IE11 để không phàn nàn. Dưới đây là phiên bản sửa đổi một chút trong những đoạn mã bút:
let cssVarPoly = {
init: function() {
// first lets see if the browser supports CSS variables
// No version of IE supports window.CSS.supports, so if that isn't supported in the first place we know CSS variables is not supported
// Edge supports supports, so check for actual variable support
if (window.CSS && window.CSS.supports && window.CSS.supports('(--foo: red)')) {
// this browser does support variables, abort
console.log('your browser supports CSS variables, aborting and letting the native support handle things.');
return;
} else {
// edge barfs on console statements if the console is not open... lame!
console.log('no support for you! polyfill all (some of) the things!!');
document.querySelector('body').classList.add('cssvars-polyfilled');
}
cssVarPoly.ratifiedVars = {};
cssVarPoly.varsByBlock = {};
cssVarPoly.oldCSS = {};
// start things off
cssVarPoly.findCSS();
cssVarPoly.updateCSS();
},
// find all the css blocks, save off the content, and look for variables
findCSS: function() {
let styleBlocks = document.querySelectorAll('style:not(.inserted),link[type="text/css"]');
// we need to track the order of the style/link elements when we save off the CSS, set a counter
let counter = 1;
// loop through all CSS blocks looking for CSS variables being set
[].forEach.call(styleBlocks, function (block) {
// console.log(block.nodeName);
let theCSS;
if (block.nodeName === 'STYLE') {
// console.log("style");
theCSS = block.innerHTML;
cssVarPoly.findSetters(theCSS, counter);
} else if (block.nodeName === 'LINK') {
// console.log("link");
cssVarPoly.getLink(block.getAttribute('href'), counter, function (counter, request) {
cssVarPoly.findSetters(request.responseText, counter);
cssVarPoly.oldCSS[counter] = request.responseText;
cssVarPoly.updateCSS();
});
theCSS = '';
}
// save off the CSS to parse through again later. the value may be empty for links that are waiting for their ajax return, but this will maintain the order
cssVarPoly.oldCSS[counter] = theCSS;
counter++;
});
},
// find all the "--variable: value" matches in a provided block of CSS and add them to the master list
findSetters: function(theCSS, counter) {
// console.log(theCSS);
cssVarPoly.varsByBlock[counter] = theCSS.match(/(--.+:.+;)/g) || [];
},
// run through all the CSS blocks to update the variables and then inject on the page
updateCSS: function() {
// first lets loop through all the variables to make sure later vars trump earlier vars
cssVarPoly.ratifySetters(cssVarPoly.varsByBlock);
// loop through the css blocks (styles and links)
for (let curCSSID in cssVarPoly.oldCSS) {
// console.log("curCSS:",oldCSS[curCSSID]);
let newCSS = cssVarPoly.replaceGetters(cssVarPoly.oldCSS[curCSSID], cssVarPoly.ratifiedVars);
// put it back into the page
// first check to see if this block exists already
if (document.querySelector('#inserted' + curCSSID)) {
// console.log("updating")
document.querySelector('#inserted' + curCSSID).innerHTML = newCSS;
} else {
// console.log("adding");
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = newCSS;
style.classList.add('inserted');
style.id = 'inserted' + curCSSID;
document.getElementsByTagName('head')[0].appendChild(style);
}
};
},
// parse a provided block of CSS looking for a provided list of variables and replace the --var-name with the correct value
replaceGetters: function(curCSS, varList) {
// console.log(varList);
for (let theVar in varList) {
// console.log(theVar);
// match the variable with the actual variable name
let getterRegex = new RegExp('var\\(\\s*' + theVar + '\\s*\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
curCSS = curCSS.replace(getterRegex, varList[theVar]);
// now check for any getters that are left that have fallbacks
let getterRegex2 = new RegExp('var\\(\\s*.+\\s*,\\s*(.+)\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
let matches = curCSS.match(getterRegex2);
if (matches) {
// console.log("matches",matches);
matches.forEach(function (match) {
// console.log(match.match(/var\(.+,\s*(.+)\)/))
// find the fallback within the getter
curCSS = curCSS.replace(match, match.match(/var\(.+,\s*(.+)\)/)[1]);
});
}
// curCSS = curCSS.replace(getterRegex2,varList[theVar]);
};
// console.log(curCSS);
return curCSS;
},
// determine the css variable name value pair and track the latest
ratifySetters: function(varList) {
// console.log("varList:",varList);
// loop through each block in order, to maintain order specificity
for (let curBlock in varList) {
let curVars = varList[curBlock];
// console.log("curVars:",curVars);
// loop through each var in the block
curVars.forEach(function (theVar) {
// console.log(theVar);
// split on the name value pair separator
let matches = theVar.split(/:\s*/);
// console.log(matches);
// put it in an object based on the varName. Each time we do this it will override a previous use and so will always have the last set be the winner
// 0 = the name, 1 = the value, strip off the ; if it is there
cssVarPoly.ratifiedVars[matches[0]] = matches[1].replace(/;/, '');
});
};
// console.log(ratifiedVars);
},
// get the CSS file (same domain for now)
getLink: function(url, counter, success) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.overrideMimeType('text/css;');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
// console.log(request.responseText);
if (typeof success === 'function') {
success(counter, request);
}
} else {
// We reached our target server, but it returned an error
console.warn('an error was returned from:', url);
}
};
request.onerror = function() {
// There was a connection error of some sort
console.warn('we could not get anything from:', url);
};
request.send();
}
};
cssVarPoly.init();
Một lựa chọn khác nhau Tôi đã sử dụng trong VS, vì nó không thích biến CSS3 trong việc rút gọn, là sass (SCSS), nó cho phép tôi tạo ra vô số biến và cũng giảm thiểu một tệp CSS dễ dàng.
Tôi đã thử phiên bản này của Polyfill nhưng đã kết thúc với lỗi khi một dòng trong CSS có nhiều biến (phông chữ FI và màu). Một đồng nghiệp của tôi đã giúp tôi. Xem dòng 94.
let cssVarPoly = {
init: function() {
// first lets see if the browser supports CSS variables
// No version of IE supports window.CSS.supports, so if that isn't supported in the first place we know CSS variables is not supported
// Edge supports supports, so check for actual variable support
if (window.CSS && window.CSS.supports && window.CSS.supports('(--foo: red)')) {
// this browser does support variables, abort
// console.log('your browser supports CSS variables, aborting and letting the native support handle things.');
return;
} else {
// edge barfs on console statements if the console is not open... lame!
// console.log('no support for you! polyfill all (some of) the things!!');
document.querySelector('body').classList.add('cssvars-polyfilled');
}
cssVarPoly.ratifiedVars = {};
cssVarPoly.varsByBlock = {};
cssVarPoly.oldCSS = {};
// start things off
cssVarPoly.findCSS();
cssVarPoly.updateCSS();
},
// find all the css blocks, save off the content, and look for variables
findCSS: function() {
let styleBlocks = document.querySelectorAll('style:not(.inserted),link[type="text/css"]');
// we need to track the order of the style/link elements when we save off the CSS, set a counter
let counter = 1;
// loop through all CSS blocks looking for CSS variables being set
[].forEach.call(styleBlocks, function (block) {
// console.log(block.nodeName);
let theCSS;
if (block.nodeName === 'STYLE') {
// console.log("style");
theCSS = block.innerHTML;
cssVarPoly.findSetters(theCSS, counter);
} else if (block.nodeName === 'LINK') {
// console.log("link");
cssVarPoly.getLink(block.getAttribute('href'), counter, function (counter, request) {
cssVarPoly.findSetters(request.responseText, counter);
cssVarPoly.oldCSS[counter] = request.responseText;
cssVarPoly.updateCSS();
});
theCSS = '';
}
// save off the CSS to parse through again later. the value may be empty for links that are waiting for their ajax return, but this will maintain the order
cssVarPoly.oldCSS[counter] = theCSS;
counter++;
});
},
// find all the "--variable: value" matches in a provided block of CSS and add them to the master list
findSetters: function(theCSS, counter) {
// console.log(theCSS);
cssVarPoly.varsByBlock[counter] = theCSS.match(/(--.+:.+;)/g) || [];
},
// run through all the CSS blocks to update the variables and then inject on the page
updateCSS: function() {
// first lets loop through all the variables to make sure later vars trump earlier vars
cssVarPoly.ratifySetters(cssVarPoly.varsByBlock);
// loop through the css blocks (styles and links)
for (let curCSSID in cssVarPoly.oldCSS) {
// console.log("curCSS:",oldCSS[curCSSID]);
let newCSS = cssVarPoly.replaceGetters(cssVarPoly.oldCSS[curCSSID], cssVarPoly.ratifiedVars);
// put it back into the page
// first check to see if this block exists already
if (document.querySelector('#inserted' + curCSSID)) {
// console.log("updating")
document.querySelector('#inserted' + curCSSID).innerHTML = newCSS;
} else {
// console.log("adding");
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = newCSS;
style.classList.add('inserted');
style.id = 'inserted' + curCSSID;
document.getElementsByTagName('head')[0].appendChild(style);
}
};
},
// parse a provided block of CSS looking for a provided list of variables and replace the --var-name with the correct value
replaceGetters: function(curCSS, varList) {
// console.log(varList);
for (let theVar in varList) {
// console.log(theVar);
// match the variable with the actual variable name
// console.log (theVar);
var res = theVar.match(/--[a-zA-Z0-9-]+/g);
// console.log (res[0]);
theVar = res[0];
let getterRegex = new RegExp('var\\(\\s*' + theVar + '\\s*\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
curCSS = curCSS.replace(getterRegex, varList[theVar]);
// now check for any getters that are left that have fallbacks
let getterRegex2 = new RegExp('var\\(\\s*.+\\s*,\\s*(.+)\\)', 'g');
// console.log(getterRegex);
// console.log(curCSS);
let matches = curCSS.match(getterRegex2);
if (matches) {
// console.log("matches",matches);
matches.forEach(function (match) {
// console.log(match.match(/var\(.+,\s*(.+)\)/))
// find the fallback within the getter
curCSS = curCSS.replace(match, match.match(/var\(.+,\s*(.+)\)/)[1]);
});
}
// curCSS = curCSS.replace(getterRegex2,varList[theVar]);
};
// console.log(curCSS);
return curCSS;
},
// determine the css variable name value pair and track the latest
ratifySetters: function(varList) {
// console.log("varList:",varList);
// loop through each block in order, to maintain order specificity
for (let curBlock in varList) {
let curVars = varList[curBlock];
// console.log("curVars:",curVars);
// loop through each var in the block
curVars.forEach(function (theVar) {
// console.log(theVar);
// split on the name value pair separator
let matches = theVar.split(/:\s*/);
// console.log(matches);
// put it in an object based on the varName. Each time we do this it will override a previous use and so will always have the last set be the winner
// 0 = the name, 1 = the value, strip off the ; if it is there
cssVarPoly.ratifiedVars[matches[0]] = matches[1].replace(/;/, '');
});
};
// console.log(ratifiedVars);
},
// get the CSS file (same domain for now)
getLink: function(url, counter, success) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.overrideMimeType('text/css;');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
// console.log(request.responseText);
if (typeof success === 'function') {
success(counter, request);
}
} else {
// We reached our target server, but it returned an error
console.warn('an error was returned from:', url);
}
};
request.onerror = function() {
// There was a connection error of some sort
console.warn('we could not get anything from:', url);
};
request.send();
}
};
cssVarPoly.init();
Có, miễn là bạn đang xử lý các thuộc tính gốc cấp tùy chỉnh (IE10 +).
- GitHub: https://github.com/jhildenbiddle/css-vars-ponyfill
- Demo: https://codepen.io/jhildenbiddle/pen/ZxYJrR
css-vars-ponyfill đã vượt quá xa những gì codepen/polyfill đề cập trong câu trả lời khác có thể xử lý.
Từ README:
Tính năng
- Client-side chuyển đổi các thuộc tính tùy chỉnh CSS để giá trị tĩnh trong các trình duyệt di sản
- Unified giao diện cho việc thay đổi các giá trị thời gian chạy trong hiện đại và di sản trình duyệt
- Thay đổi liên tục cho các cuộc gọi tiếp theo trong các trình duyệt cũ
- Hỗ trợ cho dự phòng tài sản tùy chỉnh giá trị
- UMD và ES6 module sẵn
- nhẹ (ít hơn 5k phút + gzip) và phụ thuộc miễn
Hạn chế
- hỗ trợ bất động sản Tuỳ chỉnh được giới hạn trong: khai báo gốc
- Việc sử dụng var() được giới hạn trong các giá trị thuộc tính (mỗi W3C specification)
Dưới đây là một vài ví dụ về những gì thư viện có thể xử lý:
tính Gốc tùy chỉnh cấp
:root {
--a: red;
}
p {
color: var(--a);
}
tính Tuỳ chỉnh tham khảo thuộc tính tùy chỉnh
:root {
--a: var(--b);
--b: var(--c);
--c: red;
}
p {
color: var(--a);
}
giá trị phức tạp với tính tùy chỉnh
:root {
--a: 1em;
--b: 2;
}
p {
font-size: calc(var(--a) * var(--b));
}
dự phòng đánh giá cao
p {
font-size: var(--a, 1rem);
color: var(--b, var(--c, var(--d, red)));
}
Processes CSS từ <link>
và @import
quy tắc:
<link rel="stylesheet" href="/absolute/path/to/style.css">
<link rel="stylesheet" href="../relative/path/to/style.css">
<style>
@import "/absolute/path/to/style.css";
@import "../relative/path/to/style.css";
</style>
Hy vọng điều này sẽ giúp.
(Quảng cáo tự quảng cáo không biết xấu hổ: Kiểm tra)
- 1. Actionscript3: Biến có tồn tại không?
- 2. JavaScript trong IE11 cho tôi lỗi tập lệnh 1003
- 3. Biến không tồn tại trong ngữ cảnh hiện tại?
- 4. Các tập lệnh PHP đã biên dịch có tồn tại không?
- 5. lệnh tùy biến cho Eclipse trên tập tin hiện
- 6. Có thể bỏ qua các tập tin không tồn tại, không có chủng tộc?
- 7. Các tập lệnh SQL - Có tương đương với #define tồn tại không?
- 8. Các biến lười biếng có tồn tại trong Clojure không?
- 9. Không thay đổi web.config khi không có giá trị nào tồn tại cho một biến đổi
- 10. Lệnh RabbitMQ không tồn tại?
- 11. Làm cách nào để kiểm tra xem lệnh có tồn tại trong tập lệnh shell không?
- 12. CSS Opacity không làm việc trong IE11
- 13. PHP nếu có nhiều biến tồn tại
- 14. Kiểm tra xem tên màu CSS có tồn tại không
- 15. Git liệt kê các tập tin không tồn tại không tồn tại từ từ
- 16. Kiểm tra xem một lớp CSS tồn tại mà không có jQuery
- 17. RAD cho asp.net có tồn tại không?
- 18. tập lệnh theo lô để đặt biến với vị trí đường dẫn hiện tại
- 19. Sử dụng biến bảng bên trong câu lệnh tồn tại
- 20. Liệu có tồn tại một từ khóa trong C# có thể làm cho các biến cục bộ tồn tại trên nhiều cuộc gọi không?
- 21. Tập lệnh Shell để kiểm tra xem một thư mục có tồn tại không và nếu không tạo nó?
- 22. Kiểm tra xem chương trình có tồn tại từ tập lệnh Cá hay không
- 23. biến mà vẫn tồn tại trên .pro tập tin từ một tập tin pro
- 24. Tìm hiểu xem Biến có tồn tại không
- 25. R: Tìm các biến được cung cấp cho các hàm có đối số '...' với tồn tại()
- 26. Toàn bộ tập lệnh TCL hiện tại
- 27. Làm thế nào tôi có thể phát hiện xem một biến tồn tại trong phiên Flask?
- 28. Xuất các biến giữa tập lệnh shell
- 29. Làm cách nào để kiểm tra xem một phần tử có tồn tại trong một Tập hợp các mục không?
- 30. Có tồn tại một static_warning không?
Loại biến css nào? – bhansa
https://codepen.io/aaronbarker/pen/MeaRmL –