简体   繁体   English

在使用jQuery,CSS和HTML进行选择时,如何将字体系列和大小分别应用于多个动态DIV?

[英]How do I apply font-family and size to multiple dynamic DIVs individually upon selection using jQuery, CSS and HTML?

I am using a solution I found in stackoverflow.com to apply font family and size to few dynamic DIVs. 我正在使用在stackoverflow.com中找到的解决方案,将字体系列和大小应用于少数动态DIV。 But it's applying the font-family and size on clicking of mouse after I selected desired font and size. 但是在我选择了所需的字体和大小之后,它会在单击鼠标时应用字体系列和大小。 But I want that should happen only to the selected DIV and I want to select the text in DIV first and then apply font and size. 但是我希望那只会发生在选定的DIV上,我想先选择DIV中的文本,然后再应用字体和大小。 not the reverse way. 不是相反的方式。 Can you help me? 你能帮助我吗? Below is the code: 下面是代码:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>
    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>
<br />
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery: jQuery的:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());
});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

You were on the good path, the problem was that with your Jquery you were actually saying: "When one of the drop-down is changed, modify the css of all the elements with the "changeMe" class". 您走上了一条好路,问题是您使用Jquery时实际上是在说:“当下拉列表中的一个发生更改时,请使用“ changeMe”类修改所有元素的css”。 I think the thing you actually want is something like: "When a paragraph in the div container is clicked, change the css of the clicked paragraph". 我认为您真正想要的东西是这样的:“当单击div容器中的某个段落时,请更改该单击的段落的CSS”。

I made a jsfiddle for you, it does what you want, http://jsfiddle.net/QdfmZ/ 我为您制作了一个jsfiddle,它可以满足您的要求, http://jsfiddle.net/QdfmZ/

$("#container").on('click','p',function(){
  $(this).css("font-size", $("#size").val() + "px");
  $(this).css("font-family", $("#fs").val());
});

This is the Jquery, first we tell that the div with the id "container" needs to listen to all clicks on the "p" elements. 这是Jquery,首先我们告诉ID为“ container”的div需要监听对“ p”元素的所有点击。 After that it is pretty simple, $(this) represents the clicked paragraph so we change his css with the values of the drop downs. 之后,这很简单,$(this)代表单击的段落,因此我们使用下拉列表的值更改其css。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM