一个随机句子引用(jQuery与Ajax的引用)

enter image description here

运行效果

html代码

1
2
3
4
5
6
7
8
9
10
<div class="contains">
<div class="quote">“
<span id="quoteText"> </span>”
</div>
<div class="author"> by <span id="quoteAuthor"> </span></div>
<div class="button">
<button class="quoteButton">New quote</button>
</div>
</div>

css代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@import url(https://fonts.googleapis.com/css?family=Lobster);
body {
background-color: #333;
color: #333;
font-family: 'Lobster', sans-serif;
font-size: 30px;
}
.contains {
width: 600px;
padding: 30px 40px;
margin: 8% auto auto auto;
display:table;
background-color:#fff;
border-radius: 5px;
}
.quote {
text-align: center;
width: 100%;
height: auto;
clear: both;
font-size: 2em;
font-weight: 200px;
}
.author {
text-align: right;
width: 100%;
height: auto;
clear: both;
font-size: 1em;
padding-top:20px;
}
.button {
text-align: center;
width: 100%;
}
.button .quoteButton {
height: 45px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #333;
font-size: 25px;
padding: 8px 18px 6px 18px;
margin-top:30px;
opacity:1;
}
.button:hover {
opacity:0.8;
}

js代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', '#FB6964', '#342224', "#472E32", "#BDBB99", "#77B1A9", "#73A857"];
function getQuote() {
$.ajax({
headers: {
"X-Mashape-Key": "OivH71yd3tmshl9YKzFH7BTzBVRQp1RaKLajsnafgL2aPsfP9V",
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
url: 'https://andruxnet-random-famous-quotes.p.mashape.com/cat=',
error: function(XmlHttpRequest, textStatus, errorThrown) {
alert("操作失败!");
},
success: function(response) {
var r = JSON.parse(response);
$('#quoteText').html(r.quote);
$('#quoteAuthor').html(r.author);
var color = Math.floor(Math.random() * colors.length);
$("body").animate({
backgroundColor: colors[color],
color: colors[color]
},1000);
$(".quoteButton").animate({
backgroundColor: colors[color]
},1000);
}
})
}
$(function() {
getQuote();
$(".quoteButton").click(function() {
getQuote();
})
})

运行链接:http://codepen.io/wzc/full/XNeoJg/