改变& lt; p>点击尺寸

Change <p> size on click

本文关键字:lt 改变      更新时间:2023-09-26

我试图增加<p>元素的大小,目前我有一个代码,但这个代码改变了我页面中所有<p>元素的大小,我想要的是给用户自由改变他想要的元素的大小。所以我的问题是:我该怎么做?目前我的文件如下:

$("p").click(function() {
  var fontSize = parseInt($(this).css("font-size"));
  fontSize = fontSize + 1 + "px";
  $('p').css({
    'font-size': fontSize
  });
});
$('#reset').click(function() {
  var fontSize = "8px";
  $('p').css({
    'font-size': fontSize
  });
});
p {
  font-size: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<button id="reset">Reset</button>

要更改仅单击<p>的字体大小,请尝试:

$("p").click(function() {
    var fontSize = parseInt($(this).css("font-size"));
    fontSize = fontSize + 1 + "px";
    $(this).css({'font-size':fontSize});
});

变化:

$('p').css

:

$(this).css

$(this)是指点击的<p>,而不是选择所有段落的$('p')

您应该使用$(this)而不是$('p')。因为$('p')引用dom的所有<p>标记,而$(this)将引用被单击的标记。请检查下面的代码片段。

$("p").click(function() {
    var fontSize = parseInt($(this).css("font-size"));
    fontSize = fontSize + 1 + "px";
    //In below line $(p) replaced with $(this)
    $(this).css({'font-size':fontSize});
});
$('#reset').click(function () {
  var fontSize = "8px";
  $('p').css({'font-size':fontSize});
});
p {
  font-size: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<button id="reset">Reset</button>

我认为这应该很简单:

 $('p').css({'font-size':fontSize}); 
应该

  $(this).css({'font-size':fontSize});

您可以使用this关键字来仅针对触发事件的元素,而不是针对'p'(它选择具有给定标记名称的所有元素)。

$("p").click(function() {
    var fontSize = parseInt($(this).css("font-size"));
    fontSize = fontSize + 1 + "px";
    $(this).css({'font-size':fontSize});
  
    //console.log(this);
});
$('#reset').click(function () {
  var fontSize = "8px";
  $('p').css({'font-size':fontSize});
});
p {
  font-size: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<button id="reset">Reset</button>

<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
p{
	cursor: pointer;
	font-size: 12px;
}
</style>
<body>
<h1>Do it on click</h1>
<p>A</p>
<p>B</p>
<p>C</p>
<p>D</p>
<p>E</p>
<button id="reset">Reset</button>
</body>
<script type="text/javascript">
$("p").click(function(){//fire the function when click on any p element
   var thefontsize = parseInt($(this).css("font-size"));//get the current font size
   thefontsize = thefontsize+2;//increase the font size for each click
   $(this).css({"font-size":thefontsize+"px"}); //this keyword only focus on the element which user clicke, no all the elements.
});
$("#reset").click(function(){
	$("p").css({"font-size":"12px"});
});
</script>
</html>