Can I access the value of invalid/custom CSS properties from JavaScript?

后端 未结 3 1186
清酒与你
清酒与你 2020-11-27 20:10

Assume I have the following CSS:

div {
    -my-foo: 42;
}

Can I later in JavaScript somehow know what the value of the -my-foo

3条回答
  •  一个人的身影
    2020-11-27 20:56

    In Mac 10.12.6(or other version, maybe), if you want to store some property in style like:

    text
    

    then you use span.style.getPropertyValue('--my-foo') to get, you will get the value like:

    [{'a': 'b'}]
    

    It's means that if you want to store some string/object in style(for some special purpose like .dtd limit etc.) by JSON.stringify the value, and want to parse back by JSON.parse, you will get stuck by parser err, the err message said 'single quote' not allow in JSON'.

    try below in Mac 10.12.6 Safari:

    var span = document.createElement('span');
    span.id = 'some_id';
    var data =  JSON.stringify([{d: 'e'}]);
    span.style = `--b-c: ${data}`;
    document.body.appendChild(span);
    var f = document.getElementById('some_id').style.getPropertyValue('--b-c');
    console.log('f:', f);
    

提交回复
热议问题