Js替换字符串中多个font-size: XXpx的值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37137902/article/details/81709224

HTML

 <!--文章容器-->
                <div class="uc-news-view">
                    <h3 class="til f-ellipsis" title="$model.Title" style="width:820px;">$title</h3>
                    <div class="article-attr fl">
                        <div class="tim">
                            <span class="line">$year</span>
                            <span class="month-day">$mday</span>
                        </div>
                        <div>
                            <span class="line">字号</span>
                            <span class="font-size">
                                <a href="javascript:;" size="16">大</a>
                                <a href="javascript:;" size="14" class="sel">中</a>
                                <a href="javascript:;" size="12">小</a>
                            </span>
                        </div>

                    </div>
                    <div id="nihao" class="article-content uc-paragraph fr">
                        <!--$model.Content.replace("font-size: 24px","font-size: px")-->
                    </div>
                    <script>
                        document.getElementById('nihao').innerHTML = ('\'$model.Content\'');
                    </script>
                </div>

JavaScript

  $(function () {
            //字号切换
            $(".font-size a").click(function () {

                var text = ('\'$model.Content\'');
                var regex = new RegExp('font-size', 'g');
                var count = !('\'$model.Content\'').match(regex) ? 0 : ('\'$model.Content\'').match(regex).length;
                var strLast = text;

                for (var i = 0; i < count; i++) {
                    var location = strLast.indexOf('font-size');                                     
                    var str = strLast.match(/font-size: (\S*)px/)[1];
                    var change = str;
                    if ($(this).attr("size") == 16) {
                        change = parseFloat(change) + (2 /14) * parseFloat(change);
                        text = text.replace("font-size: " + str + "px", "font-size: " + change + "px");
                    }
                    else if ($(this).attr("size") == 12) {
                        change = parseFloat(change) - (2 /14) * parseFloat(change);
                        text = text.replace("font-size: " + str + "px", "font-size: " + change + "px");
                    }

                    strLast = strLast.substring(location + 2, strLast.length );
                }
                document.getElementById('nihao').innerHTML = text;
                $(this).addClass("sel").siblings().removeClass("sel");
                $('.article-content').css({ "font-size": "" + $(this).attr("size") + "px" });               
            })
        })

猜你喜欢

转载自blog.csdn.net/m0_37137902/article/details/81709224