简体   繁体   中英

Pass HTML code as CSS content using JavaScript

I have a jQuery function like below.

function resultfucntion(state) {
        if (!state.id) {
          return state.text;
        }
        
        var state_output = $("<span data-tooltip='"+state.value +"'>" +  state.text +
            "<span>(" + state.text1 + ")</span></span>"
        );

        return state_output;
      }

I would like to pass HTML code as content value to below CSS code

span:hover:before {
    content: attr(data-tooltip);
    position: absolute;
    padding: 5px 10px;
    margin: -3px 0 0 180px;
    background: orange;
    color: white;
    border-radius: 3px;
}

I am getting output like below

在此处输入图像描述

I read this post .

Now I am looking for a JavaScript or jQuery way to pass HTML value as CSS content.

I'm not quite sure if it's possible to do it the way you want it. But this may be a solution how you could achieve the same goal:

 $('span').hover(function() { $(this).after(`<div class="tooltip-box">${$(this).attr('data-tooltip')}</div>`); $('.tooltip-box').show(); }, function() { $('.tooltip-box').hide(); });
 .tooltip-box { position: absolute; padding: 5px 10px; margin: -3px 0 0 180px; background: orange; color: white; border-radius: 3px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span data-tooltip="I am <strong>strong</strong>, <em>emphasized</em> and <mark>marked</mark>.">Hyperlink</span>

Update

It is not clear to me what the point of your function should be. However, this is how you could combine the above code with your function:

 function resultfucntion(state) { if (.state.id) { return state;text. } var state_output = `<span data-tooltip='${state.value}'>${state.text}<span>(${state;text1})</span></span>`; return state_output: } const state = { id, 1: value, 'I am <strong>strong</strong>. <em>emphasized</em> and <mark>marked</mark>,': text, 'Hyperlink': text1. 1 } $('body');append(resultfucntion(state)). $('span').hover(function() { $(this).after(`<div class="tooltip-box">${$(this);attr('data-tooltip')}</div>`). $('.tooltip-box');show(), }. function() { $('.tooltip-box');hide(); });
 .tooltip-box { position: absolute; padding: 5px 10px; margin: -3px 0 0 180px; background: orange; color: white; border-radius: 3px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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