Show image based on text value

I have a static page that shows a value in a list. This value represents the percentage of the project that was spent on each individual practice. Is there a way to display the background image in libased on the content value? I'm sure there is a javascript fix for this, but I'm not sure where to start. Javascript is not my forte.

4 values ​​will be used (25/50/75/100), and a different image will be displayed depending on the value in li.

HTML:

<div class="col-md-6">
  <ul class="list-inline stats">
    <li>25<small>Strategy</small></li>
    <li>25<small>Design</small></li>
    <li>25<small>Production</small></li>
    <li>25<small>Marketing</small></li>
  </ul>
</div>

Any help would be greatly appreciated. Thank you in advance.

+4
source share
5

JavaScript :

$('.list-inline li').addClass(function() {
   return 'bg' + this.firstChild.nodeValue;
});

css :

.bg25 { background-image: ... }    
.bg50 { background-image: ... }

http://jsfiddle.net/xcJ47/

JavaScript jQuery .css():

var bgs = {
   '25' : 'url(...)',
   '50' : 'url(...)',
   '75' : 'url(...)',
   '100': 'url(...)'
   // ...
}

$('.list-inline li').css('background-image', function() {
    return bgs[this.firstChild.nodeValue];
});
+6

- ?

HTML

<li class="percentage_li" data-percent="25">25<small>Strategy</small></li>

JQuery

var curr_percent = 0;

$(".percentage_li").each(function(){
    curr_percent = $(this).data('percent');
    $(this).css({'background-image':'url('images/'+curr_percent+'.jpg')'});
});
0

. ? li .

<li style="background-image:url('first.gif');">
<li style="background-image:url('second.gif');">
<li style="background-image:url('third.gif');">
<li style="background-image:url('fourth.gif');">
0

li, , css

$(document).ready(function(){
    var $elem = $('.list-inline li');
    var strClass = $elem.html().substr(0,2);
    $elem.addClass(strClass);
});

, , , soo,

        $elem.addClass('myNewStyle '+strClass);
0

You can use jQuery:contains() . For example ( fiddle )

$('.list-inline.stats li:contains(25)').css({background: 'red'})
$('.list-inline.stats li:contains(50)').css({background: 'green'})
$('.list-inline.stats li:contains(75)').css({background: 'blue'})
0
source

Source: https://habr.com/ru/post/1523892/


All Articles