根据按钮的宽度更改文本位置

时间:2017-05-18 12:43:23

标签: jquery html css

我正在处理一些响应式设计,并且如果某个字符串超过37个字符且按钮的宽度超过某个宽度,则希望在按钮中移动文本。

到目前为止,我设法根据string.length移动文本,但是当我介绍第二个条件时,我遇到了问题。

<div class="button">
  <p>I am a button<p>
</div>

我还有一个变量列表,可以根据以前的结果更改按钮中的文本。这是我尝试过的:

//searches my list for what text to put
var textLength = list[country].text.length

//trying to find the width of the button 
var buttonLength = $('.button').width();

//display the width, do not see it in dev tools, having issue here
console.log(buttonLength);

          if(textLength > 37 && buttonLength > 309 ){
           $('.button p').css('bottom', '0.9em'); 
          };

我认为问题可能在于我的语法。任何意见都非常感谢。

1 个答案:

答案 0 :(得分:2)

  

...如果某个字符串在上面,则想要在按钮中移动文本   37个字符并且如果按钮的宽度小于某个   宽度。

因此,你的if语句是:

if(textLength > 37 && buttonLength > 309 )

你应该试试这个:

if(textLength > 37 && buttonLength < 309 )

编辑:

由于if语句不是问题,我假设你的div有一个padding css属性,它不是用.width()方法计算的。 而是使用jQuery&#39>中提到的.outerWidth()

  

获取当前计算的外部宽度(包括填充,边框和   对于匹配集合中的第一个元素,可选择margin)   元素或设置每个匹配元素的外部宽度。

这是一个工作小提琴:

&#13;
&#13;
var textLength = $('#text').html().length,
		divWidth = $('#test').outerWidth();

if (textLength > 14 && divWidth > 300) {
	alert("Text is "+ textLength + " characters, div is " + divWidth+ "px wide");
  $('#text').css('transform', 'translateY(0.9em)');
}
else {
	alert("Not in condition");
}
&#13;
#test {
  display: block;
  float: left;
  padding: 0 100px;
  background: springgreen;
  width: auto;
  position: relative;
}
#text {
  display: inline-block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<div id="test">
<p id="text">fsqdfdgfdgfdfgdf</p>
</div>
&#13;
&#13;
&#13;

此外,请使用bottom: 0.9em属性,而不是transform